Follow links to add evaluation to evaluate
T = 0.2
Prompt Override = insert
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Fail | Fail | Fail |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Pass | Pass | Pass | Pass | Pass |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Fail | Pass | Pass | Pass | Fail |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Fail | Pass | Pass | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Pass | Pass | Pass | Pass | Pass |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Pass | Fail | Pass | Fail | Fail |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Fail | Pass | Pass | Pass |
| cubes | Pass | Pass | Pass | Pass | Pass |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Pass | Fail | Fail | Pass | Pass |
| dipole | Pass | Pass | Pass | Pass | Pass |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Fail | Pass | Pass |
| element_mass | Fail | Pass | Fail | Fail | Fail |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Pass | Pass | Pass | Pass | Pass |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Pass | Pass | Fail | Pass |
| freezing_depression | Pass | Pass | Pass | Pass | Fail |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Pass |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Pass | Pass | Pass | Pass | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Pass | Pass | Pass | Pass | Pass |
| langevin_dynamics | Pass | Fail | Fail | Fail | Fail |
| weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
| lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Pass | Pass | Pass | Pass | Pass |
| matrix_factorial | Pass | Pass | Pass | Pass | Pass |
| max-boltz | Pass | Pass | Fail | Pass | Pass |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Fail | Fail | Fail | Fail | Fail |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Pass |
| pred_interval | Fail | Pass | Fail | Fail | Fail |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Fail | Fail | Pass | Fail |
| random_walk | Pass | Pass | Pass | Fail | Pass |
| rank | Pass | Pass | Pass | Pass | Pass |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Pass | Pass | Pass | Pass | Pass |
| rms_velocity | Pass | Pass | Fail | Fail | Pass |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Fail | Fail | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Fail |
| seq-trans | Pass | Pass | Pass | Pass | Fail |
| sequence | Fail | Pass | Fail | Fail | Pass |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Pass | Pass | Pass | Pass | Pass |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Pass | Fail | Pass | Pass | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for amino_acid in sequence:
if amino_acid in ['S', 'T', 'N', 'Q', 'H', 'K', 'R']:
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'H' or i == 'D' or i == 'E' or i == 'S' or i == 'T' or i == 'N' or i == 'Q' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == 'R' or i == 'K' or i == 'D' or i == 'E' or i == 'Q' or i == 'N' or i == 'H' or i == 'S' or i == 'T' or i == 'Y' or i == 'C' or i == 'M' or i == 'W':
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == "S" or i == "T" or i == "N" or i == "Q" or i == "H" or i == "K" or i == "R":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for i in sequence:
if i == "R" or i == "K" or i == "E" or i == "D" or i == "Q" or i == "N" or i == "H" or i == "S" or i == "T" or i == "Y" or i == "C" or i == "M" or i == "W":
count += 1
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj.superpose(traj, frame=frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
Success
angle
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1 = np.array(v1)
v2 = np.array(v2)
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
v1_u = v1/np.linalg.norm(v1)
v2_u = v2/np.linalg.norm(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
if np.isnan(angle):
if (v1_u == v2_u).all():
return 0.0
else:
return np.pi
return angle
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
cosang = np.dot(v1,v2)
sinang = np.linalg.norm(np.cross(v1,v2))
angle = np.arctan2(sinang,cosang)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic = ['F', 'Y', 'W']
count = 0
for i in sequence:
if i in aromatic:
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for i in sequence:
if i == 'F' or i == 'Y' or i == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_list = ['F', 'Y', 'W']
count = 0
for aa in sequence:
if aa in aromatic_list:
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for aa in sequence:
if aa == 'F' or aa == 'Y' or aa == 'W':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea)/(8.314*T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2 * math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((Ea/8.314)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
c1 = 3.74177e-16
c2 = 1.4388e-2
B = c1/(lam**5 * (np.exp(c2/(lam*T)) - 1))
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 3.0e8
k = 1.38064852e-23
B = 2*h*c**2/(lam**5)*1/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = (2*h*c**2)/(lam**5*(np.exp((h*c)/(lam*k*T))-1))
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
B = 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'DATABASE': 'nr', 'PROGRAM': 'blastp', 'CMD': 'Put'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
result = soup.find('pre').text
# 4. Parse MSA
lines = result.split('\n')
msa = []
for line in lines:
if line.startswith('>'):
msa.append(line)
# 5. Return a tuple of e score, id of top match
e = float(msa[1].split()[-1])
id = msa[0].split()[1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'text'
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq,
'PROGRAM': 'blastn',
'DATABASE': 'refseq_rna',
'FILTER': 'L',
'EXPECT': '10',
'HITLIST_SIZE': '1',
'ALIGNMENTS': '50',
'DESCRIPTIONS': '50',
'FORMAT_TYPE': 'HTML',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'PAGE': 'Nucleotides',
'CMD': 'Put'}
r = requests.get(url, params=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
alignments = soup.find_all('pre')
alignments = [x.text for x in alignments]
alignments = [x.split('\n') for x in alignments]
alignments = [x for x in alignments if len(x) > 1]
alignments = [x for x in alignments if x[0].startswith('Query')]
alignments = [x for x in alignments if x[1].startswith('Sbjct')]
alignments = [x for x in alignments if len(x) > 2]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x for x in alignments if x[-1].startswith('Score')]
alignments = [x
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
invalid syntax (<string>, line 69)
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
import requests
from bs4 import BeautifulSoup
# 2.
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'PAGE': 'Nucleotides',
'PROGRAM': 'blastn',
'DATABASE': 'nr',
'QUERY': seq,
'CMD': 'Put'}
r = requests.post(url, data=params)
# 3.
url = r.url.replace('Put', 'Get')
r = requests.get(url)
# 4.
soup = BeautifulSoup(r.text, 'html.parser')
msa = soup.find_all('pre')[0].text
msa = msa.split('\n')
# 5.
e = msa[1].split()[-1]
id = msa[0].split()[-1]
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'https://blast.ncbi.nlm.nih.gov/Blast.cgi'
params = {'QUERY': seq, 'PROGRAM': 'blastp', 'DATABASE': 'nr', 'CMD': 'Put'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
res = soup.find_all('pre')[0].text.split('\n')
# 4. Parse MSA
msa = []
for line in res:
if line.startswith('>'):
msa.append(line)
elif line.startswith(' Score ='):
e = float(line.split('=')[1].split('bits')[0].strip())
elif line.startswith(' Identities ='):
id = float(line.split('=')[1].split('/')[0].strip())
# 5. Return a tuple of e score, id of top match
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1.
from Bio.Blast import NCBIWWW
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from Bio.Blast import NCBIXML
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2.
result_handle = NCBIWWW.qblast("blastp", "nr", seq)
# 3.
blast_records = NCBIXML.parse(result_handle)
# 4.
for blast_record in blast_records:
for alignment in blast_record.alignments:
for hsp in alignment.hsps:
print('****Alignment****')
print('sequence:', alignment.title)
print('length:', alignment.length)
print('e value:', hsp.expect)
print(hsp.query[0:75] + '...')
print(hsp.match[0:75] + '...')
print(hsp.sbjct[0:75] + '...')
# 5.
e = hsp.expect
id = alignment.title
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
Timeout
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
name = None
if group_number in range(1, 3):
name = 'triclinic'
elif group_number in range(3, 16):
name = 'monoclinic'
elif group_number in range(16, 75):
name = 'orthorhombic'
elif group_number in range(75, 143):
name = 'tetragonal'
elif group_number in range(143, 168):
name = 'trigonal'
elif group_number in range(168, 195):
name = 'hexagonal'
elif group_number in range(195, 231):
name = 'cubic'
else:
sys.exit('Space group number out of range')
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 1 or group_number > 230:
print("Invalid space group number")
sys.exit()
name = ""
if group_number <= 2:
name = "triclinic"
elif group_number <= 15:
name = "monoclinic"
elif group_number <= 74:
name = "orthorhombic"
elif group_number <= 142:
name = "tetragonal"
elif group_number <= 167:
name = "trigonal"
elif group_number <= 194:
name = "hexagonal"
elif group_number <= 230:
name = "cubic"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in range(1, 3):
name = "triclinic"
elif group_number in range(3, 16):
name = "monoclinic"
elif group_number in range(16, 75):
name = "orthorhombic"
elif group_number in range(75, 143):
name = "tetragonal"
elif group_number in range(143, 168):
name = "trigonal"
elif group_number in range(168, 195):
name = "hexagonal"
elif group_number in range(195, 231):
name = "cubic"
else:
print("Space group number not recognized")
sys.exit()
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number < 3:
name = "triclinic"
elif group_number < 16:
name = "monoclinic"
elif group_number < 75:
name = "orthorhombic"
elif group_number < 143:
name = "tetragonal"
elif group_number < 168:
name = "trigonal"
elif group_number < 195:
name = "hexagonal"
elif group_number < 231:
name = "cubic"
else:
name = "unknown"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number > 0 and group_number < 3:
name = "triclinic"
elif group_number > 2 and group_number < 16:
name = "monoclinic"
elif group_number > 15 and group_number < 75:
name = "orthorhombic"
elif group_number > 74 and group_number < 143:
name = "tetragonal"
elif group_number > 142 and group_number < 168:
name = "trigonal"
elif group_number > 167 and group_number < 195:
name = "hexagonal"
elif group_number > 194 and group_number < 231:
name = "cubic"
else:
name = "unknown"
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - T_cold/T_hot
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - (T_cold/T_hot)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = 1 - T_cold/T_hot
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp(HVap*(1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap/8.314)*((1/T1)-(1/T2)))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 * math.exp(HVap * (1/T1 - 1/T2))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1*math.exp((HVap*1000)/(8.314*T1)*(1/T2-1/T1))
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
if mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity:
result = True
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = False
e1 = mendeleev.element(element1)
e2 = mendeleev.element(element2)
if e1.electronegativity > e2.electronegativity:
result = True
return result
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
if element1 not in mendeleev.element or element2 not in mendeleev.element:
print("Error: element not found")
sys.exit()
if mendeleev.element[element1].pauling_electronegativity > mendeleev.element[element2].pauling_electronegativity:
result = True
else:
result = False
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
argument of type 'function' is not iterable
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(x.shape)
diff[1:] = x[1:] - x[:-1]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
operands could not be broadcast together with shapes (4,) (5,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.zeros(len(x)-1)
for i in range(len(x)-1):
diff[i] = x[i+1] - x[i]
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = 0
for i in range(1, n+1):
s += i**3
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606957e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = h/(m*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x + b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
d = 2*a*x+b
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = 2*a*x + b
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([Descriptors.MolWt(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.TPSA(mol),
Descriptors.LabuteASA(mol),
Descriptors.ExactMolWt(mol)])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(np.array(MoleculeDescriptors.MolecularDescriptorCalculator(nms).CalcDescriptors(mol)))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(np.array(MoleculeDescriptors.MolecularDescriptorCalculator([x[0] for x in Descriptors._descList]).CalcDescriptors(mol)))
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([
Descriptors.MolWt(mol),
Descriptors.MolLogP(mol),
Descriptors.TPSA(mol),
Descriptors.NumHDonors(mol),
Descriptors.NumHAcceptors(mol),
Descriptors.NumRotatableBonds(mol),
Descriptors.NumValenceElectrons(mol),
Descriptors.NumRadicalElectrons(mol)
])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append([rdMolDescriptors.CalcExactMolWt(mol),
rdMolDescriptors.CalcTPSA(mol),
rdMolDescriptors.CalcNumRotatableBonds(mol),
rdMolDescriptors.CalcNumHBA(mol),
rdMolDescriptors.CalcNumHBD(mol),
rdMolDescriptors.CalcNumHeteroatoms(mol),
rdMolDescriptors.CalcNumRings(mol),
rdMolDescriptors.CalcNumAromaticRings(mol)])
descriptors = np.array(descriptors)
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros([3])
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i]*coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i]*coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.sum(coordinates*charges[:,np.newaxis], axis=0)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
d = []
for s in smiles:
m = Chem.MolFromSmiles(s)
d.append(Descriptors.NumRotatableBonds(m))
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Python argument types in
rdkit.Chem.rdMolDescriptors.CalcNumRotatableBonds(NoneType)
did not match C++ signature:
CalcNumRotatableBonds(RDKit::ROMol mol, RDKit::Descriptors::NumRotatableBondsOptions strict=rdkit.Chem.rdMolDescriptors.NumRotatableBondsOptions.Default)
CalcNumRotatableBonds(RDKit::ROMol mol, bool strict)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
m = Chem.MolFromSmiles(smiles)
d = Descriptors.NumRadicalElectrons(m)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRotatableBonds(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
return Descriptors.NumRadicalElectrons(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
C = rdMolDescriptors.CalcNumAliphaticCarbocycles(mol)
N = rdMolDescriptors.CalcNumAliphaticHeterocycles(mol)
H = rdMolDescriptors.CalcNumAliphaticHydrogen(mol)
X = rdMolDescriptors.CalcNumAliphaticHalogen(mol)
d = 2*(C+N+X) - 2 + H
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
module 'rdkit.Chem.rdMolDescriptors' has no attribute 'CalcNumAliphaticHydrogen'
eigen-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
[insert]
return w,vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
w = np.real(w)
v = np.real(v)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w,v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element not found"
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element not found")? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
mass = element.mass
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element symbol not found"
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element symbol not found")? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: Element mass not found for element %s" % element_symbol
sys.exit()
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: Element mass not found for element %s" % element_symbol)? (<string>, line 12)
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.element(element_symbol).mass
if mass == None:
print "Error: element mass not found for element %s" % element_symbol
sys.exit(1)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Missing parentheses in call to 'print'. Did you mean print("Error: element mass not found for element %s" % element_symbol)? (<string>, line 12)
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
if s == 'D':
s = 'H'
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.element(element_number).symbol
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6 * (1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = -13.6*(1/n**2)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')
idx = idx[0:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')
idx = idx[0:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
idx = np.where(traj.topology.select('name CA'))[0][:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
idx = topology.select('name CA')
idx = idx[:2]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (m1*m2)/(m1+m2)*(wave_len*1.0e-2)**2
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (m1*m2)/(m1+m2)*(wave_len*1.0e-2)**2*1.0e-8
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.98644568e-23 * 299792458**2 * 1e2 * (m1*m2)/(m1+m2)) / (wave_len*1e-2)**2
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (m1*m2)/(m1+m2)*(2*np.pi*1.99e-23*1e-2/(wave_len*1e-2))**2
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = (1.0/wave_len)*(1.0/wave_len)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
fourier_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=np.complex)
for i in range(N):
for j in range(N):
w[i] += x[j]*np.exp(-2j*np.pi*i*j/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
w[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N)
for k in range(N):
for n in range(N):
w[k] += x[n]*np.exp(-2*np.pi*1j*k*n/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
w = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
w[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m
if deltaT < 0:
print("Error: deltaT is negative")
sys.exit(1)
else:
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
expected an indented block (<string>, line 16)
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
table = soup.find_all('table')[0]
generators = []
for row in table.find_all('tr'):
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([float(ele) for ele in cols])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([float(ele) for ele in cols])
generators = np.array(generators)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_gen"
params = {'gnum': gnum}
r = requests.get(url, params=params)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table')
generators = []
for row in table.findAll('tr'):
col = row.findAll('td')
if len(col) > 0:
generators.append(np.array([[float(col[0].text), float(col[1].text), float(col[2].text)],
[float(col[3].text), float(col[4].text), float(col[5].text)],
[float(col[6].text), float(col[7].text), float(col[8].text)]]))
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'findAll'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matrix_generators?gnum=' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
table = soup.find('table')
generators = []
for row in table.findAll('tr'):
cells = row.findAll('td')
if len(cells) == 4:
generators.append([float(cells[0].find(text=True)), float(cells[1].find(text=True)), float(cells[2].find(text=True)), float(cells[3].find(text=True))])
generators = np.array(generators)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'findAll'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-matgen?gnum=' + str(gnum)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = np.array(generators)
generators = generators[1:,1:]
generators = generators.astype(float)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * (4.184 * (T2 - T1))
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = n * 4.184 * (T2 - T1)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for atom in traj.topology.atoms:
if atom.element.symbol == 'C':
resids.append(atom.residue.index)
resids = np.unique(resids)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for res in traj.topology.residues:
if res.is_water:
continue
if res.is_protein:
if res.name in ['ALA', 'VAL', 'LEU', 'ILE', 'MET', 'PHE', 'TRP', 'PRO']:
resids.append(res.index)
resids = np.array(resids)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i, res in enumerate(traj.topology.residues):
if res.is_water:
continue
if res.is_protein:
if res.name in ['ALA', 'ILE', 'LEU', 'VAL', 'PHE', 'TRP', 'TYR', 'MET']:
resids.append(i)
resids = np.array(resids)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
traj = md.load(pdb_filename)
resids = []
for i in range(traj.n_residues):
if traj.topology.residue(i).is_hydrophobic:
resids.append(i)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm*L/mol/K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 #atm L / mol K
P = n*R*T/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 # atm L / mol K
P = (n * R * T) / V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.0821 # atm L / mol K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
P = (n*R*T)/V
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = (a/4)*(b**4) + (b/3)*(b**3) + (c/2)*(b**2) + d*b
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
x = np.linspace(0,1,100)
y = a*x**3 + b*x**2 + c*x + d
integral = np.trapz(y,x)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
x = np.linspace(0,10,100)
y = a*x**3 + b*x**2 + c*x + d
integral = np.trapz(y,x)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
x = np.linspace(0,1,100)
y = a*x**3 + b*x**2 + c*x + d
integral = np.trapz(y,x)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
x = np.linspace(0,10,100)
y = a*x**3 + b*x**2 + c*x + d
integral = np.trapz(y,x)
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
trap
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
x = np.linspace(a, b, n+1)
h = (b-a)/n
integral = 0.5*h*(f(a) + f(b))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
integral = 0.5*(f(a) + f(b))
for i in range(1, n):
integral += f(a + i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
x = np.linspace(a, b, n+1)
h = (b-a)/n
integral = 0.5*h*(f(x[0]) + f(x[-1]))
for i in range(1, n):
integral += h*f(x[i])
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
integral = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
integral += f(a + i * h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
integral = 0.5*f(a) + 0.5*f(b)
for i in range(1,n):
integral += f(a+i*h)
integral *= h
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
m = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(m)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
SMILES = Chem.MolToSmiles(mol)
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
kld
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(true_data * np.log(true_data / predicted_data))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt - (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T/m)*np.random.normal(0,1)*np.sqrt(dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i]*(1-gamma*dt/m) + F(x_traj[i])*dt/m + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = (v_traj[i] - (F(x_traj[i])/m)*dt - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T*dt)*np.random.normal())/(1+gamma*dt)
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + dt*v_traj[i]
v_traj[i+1] = v_traj[i] - dt*F(x_traj[i])/m - dt*gamma*v_traj[i] + np.sqrt(2*gamma*T*dt)*np.random.normal()
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T*w*x).I*x.T*w*y
beta = np.array(beta)
return beta
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = (x.T * w * x).I * x.T * w * y
return beta
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
X = np.vstack([x, np.ones(len(x))]).T
beta = np.linalg.inv(X.T.dot(np.diag(w)).dot(X)).dot(X.T).dot(np.diag(w)).dot(y)
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 100
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
X = np.matrix(x)
Y = np.matrix(y)
W = np.matrix(np.diag(w))
beta = (X.T * W * X).I * X.T * W * Y
return beta
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
x = np.matrix(x)
y = np.matrix(y)
w = np.matrix(w)
beta = np.linalg.inv(x.T * w * x) * x.T * w * y
return beta
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,100) and (1,100) not aligned: 100 (dim 1) != 1 (dim 0)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
else:
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if Descriptors.NumHDonors(mol) > 5:
result = False
if Descriptors.NumHAcceptors(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
result = True
if rdMolDescriptors.CalcNumHBD(mol) > 5:
result = False
if rdMolDescriptors.CalcNumHBA(mol) > 10:
result = False
if Descriptors.MolWt(mol) > 500:
result = False
if Crippen.MolLogP(mol) > 5:
result = False
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e /= len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i] - y[i])/y[i]
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = 0
for i in range(len(y)):
e += abs(y_hat[i]-y[i])/y[i]
e = e/len(y)
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), molecule.n_atoms))
for i, bead in enumerate(beads_mappings):
M[i, bead.indices] = bead.masses / bead.masses.sum()
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule.atoms), len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.atoms.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.atoms.indices, i] = bead.atoms.masses
M /= np.sum(M, axis=0)
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'atoms'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.atoms.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = bead.masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'masses'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.atoms.n_atoms, len(beads_mappings)))
for i, bead in enumerate(beads_mappings):
M[bead.indices, i] = 1.0
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
matpow
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n%2 == 0:
return matpow(x.dot(x),n/2)
else:
return x.dot(matpow(x.dot(x),(n-1)/2))
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.eye(x.shape[0])
for i in range(n):
r = np.dot(r,x)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros(n.shape)
for i in range(n.shape[0]):
for j in range(n.shape[1]):
f[i,j] = np.math.factorial(n[i,j])
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
Success
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23 # Boltzmann constant in J/K
s = math.sqrt(k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23
s = math.sqrt(3*k*T/M)
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax*S/(Km+S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S / (Km + S)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
charge = round(charge,2)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Descriptors.MolWt(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'K' or i == 'R':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
pass
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in range(len(sequence)):
if sequence[i] == 'K' or sequence[i] == 'R':
charge += 1
elif sequence[i] == 'D' or sequence[i] == 'E':
charge -= 1
else:
pass
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'R' or i == 'K':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for i in sequence:
if i == 'K' or i == 'R':
charge += 1
elif i == 'D' or i == 'E':
charge -= 1
else:
charge += 0
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
else:
pass
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
# Initialize the solution array
sol = np.zeros((len(y0), len(t)))
sol[:,0] = y0
# Solve the ODE
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], sol[:,i])
k2 = fn(t[i] + h/4, sol[:,i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, sol[:,i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, sol[:,i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, sol[:,i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, sol[:,i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
sol[:,i+1] = sol[:,i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0,:] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], sol[i,:])
k2 = h*fn(t[i] + h/4, sol[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, sol[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, sol[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, sol[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, sol[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
sol[i+1,:] = sol[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
n = len(t)
y = np.zeros((n,len(y0)))
y[0] = y0
for i in range(n-1):
h = t[i+1]-t[i]
k1 = h*fn(t[i],y[i])
k2 = h*fn(t[i]+h/4,y[i]+k1/4)
k3 = h*fn(t[i]+3*h/8,y[i]+3*k1/32+9*k2/32)
k4 = h*fn(t[i]+12*h/13,y[i]+1932*k1/2197-7200*k2/2197+7296*k3/2197)
k5 = h*fn(t[i]+h,y[i]+439*k1/216-8*k2+3680*k3/513-845*k4/4104)
k6 = h*fn(t[i]+h/2,y[i]-8*k1/27+2*k2-3544*k3/2565+1859*k4/4104-11*k5/40)
y[i+1] = y[i] + 25*k1/216+1408*k3/2565+2197*k4/4104-k5/5
return y
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], sol[i])
k2 = h * fn(t[i] + h/4, sol[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, sol[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, sol[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, sol[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, sol[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
sol[i+1] = sol[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros((len(t), len(y0)))
sol[0] = y0
for i in range(len(t)-1):
k1 = fn(t[i], sol[i])
k2 = fn(t[i] + t[i+1]/4, sol[i] + k1*t[i+1]/4)
k3 = fn(t[i] + 3*t[i+1]/8, sol[i] + 3*k1*t[i+1]/32 + 9*k2*t[i+1]/32)
k4 = fn(t[i] + 12*t[i+1]/13, sol[i] + 1932*k1*t[i+1]/2197 - 7200*k2*t[i+1]/2197 + 7296*k3*t[i+1]/2197)
k5 = fn(t[i] + t[i+1], sol[i] + 439*k1*t[i+1]/216 - 8*k2*t[i+1] + 3680*k3*t[i+1]/513 - 845*k4*t[i+1]/4104)
k6 = fn(t[i] + t[i+1]/2, sol[i] - 8*k1*t[i+1]/27 + 2*k2*t[i+1] - 3544*k3*t[i+1]/2565 + 1859*k4*t[i+1]/4104 - 11*k5*t[i+1]/40)
sol[i+1] = sol[i] + t[i+1]*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return sol
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i, k in enumerate(a):
v[i, k] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros((len(a), len(set(a))))
for i in range(len(a)):
v[i, a[i]] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi / R / T
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = Pi/(R*T)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.tril(distances)
distances = distances[distances > 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.tril(distances)
distances = distances[distances > 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = np.tril(distances)
distances = distances[distances > 0]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
topology = traj.topology
alpha_carbons = topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = np.triu(distances)
distances = distances[np.nonzero(distances)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
traj = md.load(pdb_file)
alpha_carbons = traj.topology.select('name CA')
distances = md.compute_distances(traj, alpha_carbons, periodic=False)
distances = distances[0]
distances = distances[np.triu_indices(len(alpha_carbons), k=1)]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(-1, 1, nsamples)
y = np.random.uniform(-1, 1, nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4.0 * np.sum(r < 1.0) / nsamples
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.rand(nsamples)
y = np.random.rand(nsamples)
pi_est = 4.0*np.sum(x**2 + y**2 < 1.0)/nsamples
plt.plot(x,y,'.')
plt.savefig('pi.png')
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(-1,1,nsamples)
y = np.random.uniform(-1,1,nsamples)
r = np.sqrt(x**2 + y**2)
pi_est = 4*np.sum(r<1)/nsamples
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2*math.pi**2*hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e = (n**2 * math.pi**2 * hbar**2)/(2*m*L**2)
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 0
while (1-p)**n < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 1
while np.sum(p*(1-p)**np.arange(n)) < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 0
while p**n < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 0
prob = 1
while prob > pred_level:
prob *= (1-p)
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = 1
while (1 - p)**(n-1) * p < pred_level:
n += 1
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Timeout
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT".format(smiles)
response = requests.get(url)
cids = response.text.split()
cids = [int(cid) for cid in cids]
mols = []
for cid in cids:
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
invalid literal for int() with base 10: 'Status:'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split("\n")
cids = [cid for cid in cids if cid != ""]
cids = ",".join(cids)
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % cids
response = requests.get(url)
mols = response.text.split("\n")
mols = [mol for mol in mols if mol != ""]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT'.format(smiles)
response = requests.get(url)
cids = response.text.split('\n')
cids = [cid for cid in cids if cid != '']
cids = cids[:10]
mols = []
for cid in cids:
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT'.format(cid)
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
r = requests.get(url)
cids = r.text.split()
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
r = requests.get(url)
mols = r.text.split()
return mols
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/similarity/smiles/{}/cids/TXT".format(smiles)
response = requests.get(url)
cids = response.text.split()
cids = cids[:10]
mols = []
for cid in cids:
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/{}/property/CanonicalSMILES/TXT".format(cid)
response = requests.get(url)
mols.append(response.text)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
#print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print("Ground state energy for {} in {} basis is {}".format(atom,basis,ground_energy))
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
print("Ground state energy:",ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom, basis=basis, verbose=0)
mf = pyscf.scf.RHF(mol)
mf.kernel()
ground_energy = mf.e_tot
#print(ground_energy)
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
result = Crippen.MolLogP(mol)
return result
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q * 100)
return result
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
if not isinstance(q, np.ndarray):
q = np.array([q])
result = np.zeros(q.shape)
for i in range(q.size):
result[i] = np.percentile(a, q[i]*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
index 1 is out of bounds for axis 0 with size 1
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.array(a)
if np.isscalar(q):
q = np.array([q])
else:
q = np.array(q)
assert np.all(q >= 0) and np.all(q <= 1), "Quantiles must be between 0 and 1 inclusive."
result = np.empty(q.shape)
for i, qi in enumerate(q):
if qi == 0:
result[i] = np.min(a)
elif qi == 1:
result[i] = np.max(a)
else:
result[i] = np.percentile(a, qi * 100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.percentile(a, q*100)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
random_walk
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
traj[0] = x0
for i in range(1,N):
traj[i] = traj[i-1] + a*(np.random.randint(2)*2-1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
x = x0 + a*(2*np.random.randint(2)-1)
traj[i] = x
x0 = x
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
if np.random.rand() < 0.5:
traj[i] = x0 + a
else:
traj[i] = x0 - a
x0 = traj[i]
return traj
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N+1)
traj[0] = x0
for i in range(1,N+1):
traj[i] = traj[i-1] + a*np.random.choice([-1,1])
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = np.zeros(N)
for i in range(N):
x = x0 + a*(2*np.random.randint(2)-1)
traj[i] = x
x0 = x
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-10)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M, full_matrices=False)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-6)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.sum(s > 1e-12)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
r = np.sum(S > 1e-6)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
water_indices = top.select('water')
new_traj = traj.atom_slice(np.setdiff1d(np.arange(traj.n_atoms),water_indices))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
new_traj = traj.atom_slice(traj.topology.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
new_traj = traj.atom_slice(top.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
top = traj.topology
water_indices = top.select('water')
new_traj = traj.atom_slice(np.setdiff1d(np.arange(traj.n_atoms),water_indices))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
new_traj = traj.atom_slice(traj.topology.select('not water'))
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # Boltzmann constant in J/K
m = m*1.6605e-27 # mass in kg
v_rms = math.sqrt(3*k*T/m)
print("The root-mean-squared velocity of a molecule of mass",m,"is",v_rms,"m/s")
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 #J/K
m = m*1.6605e-27 #kg
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 #J/K
m = m*1.66054e-24 #g to amu
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23
m = m*1.66054e-24
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23 # m^2 kg s^-2 K^-1
m = m * 1.660539040e-27 # kg
v_rms = math.sqrt(3*k*T/m)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt(np.mean((a-b)**2))
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
rg = md.compute_rg(traj)
rg = np.mean(rg)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
axis 1 is out of bounds for array of dimension 1
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = sasa[0]
sasa = np.sum(sasa, axis=1)
sasa = sasa.tolist()
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
axis 1 is out of bounds for array of dimension 1
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=0)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
sasa = np.sum(sasa, axis=1)
sasa = np.sum(sasa, axis=1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
axis 1 is out of bounds for array of dimension 1
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(Scaffolds.MurckoScaffoldSmiles(mol))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(smiles)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Scaffolds.MurckoScaffoldSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffoldSmiles'
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = pairwise2.format_alignment(*alns[0])
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
aligned = alns[0][0]
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aligned = pairwise2.format_alignment(*top_aln)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aligned = pairwise2.format_alignment(*top_aln)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aligned = pairwise2.format_alignment(*top_aln)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq).translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = gene_seq.translate()
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
translate() takes exactly one argument (0 given)
sequence
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.zeros(l)
x[0] = s
for i in range(1,l):
x[i] = x[i-1]*e
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.logspace(np.log10(s),np.log10(e),num=l)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.zeros(l)
x[0] = s
for i in range(1,l):
x[i] = x[i-1]*e
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.linspace(s,e,l)
x = np.power(10,x)
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.zeros(l)
for i in range(l):
x[i] = s*(e/s)**(i/(l-1))
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
x = sympy.solve(eqns)
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigvals))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigval = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigval))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigval = np.linalg.eigvals(a)
sradius = np.max(np.abs(eigval))
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
max_idx = np.argmax(abs_spectrum[:, 1])
wavenumbers.append(abs_spectrum[max_idx, 0])
abs_spectrum[max_idx, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
max_index = np.argmax(abs_spectrum[:, 1])
max_wavenumber = abs_spectrum[max_index, 0]
wavenumbers.append(max_wavenumber)
abs_spectrum[max_index-10:max_index+10, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1, distance=10)
peaks = peaks[0]
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])]
peaks = peaks[-npeaks:]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
wavenumbers = []
for i in range(npeaks):
peak_index = np.argmax(abs_spectrum[:, 1])
peak_wavenumber = abs_spectrum[peak_index, 0]
wavenumbers.append(peak_wavenumber)
abs_spectrum[peak_index, 1] = 0
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:, 1], height=0.1)
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])][::-1][:npeaks]
wavenumbers = abs_spectrum[peaks, 0]
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 #J/mol/K
s = math.sqrt(gamma*R*T/m)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
idx = []
for i in range(len(mol_list)):
if mol_list[i].HasSubstructMatch(Chem.MolFromSmiles(smiles)):
idx.append(i)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolHash.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(s), 2, nBits=bits) for s in smiles_list]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.rdMolHash' has no attribute 'GetMorganFingerprintAsBitVect'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
s = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
s[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return s
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smiles) for smiles in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
mols = [Chem.MolFromSmiles(smile) for smile in smiles_list]
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, 2, nBits=bits) for mol in mols]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
top = traj.topology
lig_res = top.select('resname '+lig_str)
prot_res = top.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_res))
result = md.compute_distances(traj,[lig_com,prot_com])
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
top = traj.topology
lig_ind = top.select('resname '+lig_str)
prot_ind = top.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
result = md.compute_distances(traj,[lig_com,prot_com])
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_res = traj.topology.select('resname '+lig_str)
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_res))
prot_com = md.compute_center_of_mass(traj.atom_slice(traj.topology.select('protein')))
result = np.linalg.norm(lig_com-prot_com,axis=1)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
prot_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
result = md.compute_distances(traj,[lig_com,prot_com],periodic=False)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_sel = traj.topology.select('resname '+lig_str)
prot_sel = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_sel))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_sel))
result = np.sqrt(np.sum((lig_com-prot_com)**2,axis=1))
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Pass | Fail | Pass |
| adiabatic_expansion | Pass | Pass | Pass | Pass | Pass |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Pass | Pass | Pass | Pass | Pass |
| arrhenius | Pass | Fail | Fail | Pass | Fail |
| bimolecular | Pass | Pass | Pass | Pass | Pass |
| bb_rad | Pass | Pass | Fail | Pass | Pass |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Fail | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Pass | Pass | Pass | Pass | Pass |
| claussius | Pass | Fail | Pass | Pass | Pass |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Fail | Pass |
| cubes | Pass | Pass | Fail | Pass | Fail |
| de_broglie | Pass | Pass | Pass | Pass | Pass |
| derivative1d-ch | Pass | Pass | Pass | Pass | Pass |
| derivative_2deg | Pass | Pass | Pass | Pass | Pass |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Pass | Pass | Pass | Pass | Pass |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Pass | Pass | Pass | Fail | Pass |
| eigen | Pass | Fail | Pass | Pass | Pass |
| element_mass | Pass | Pass | Pass | Pass | Pass |
| element_name | Pass | Pass | Pass | Pass | Pass |
| energy_of_e | Pass | Pass | Fail | Pass | Fail |
| find_indices | Pass | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Pass | Pass | Pass | Pass |
| freezing_depression | Pass | Pass | Pass | Pass | Pass |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Fail | Fail | Fail |
| hydrophobic_res | Pass | Fail | Pass | Fail | Fail |
| ideal_gas | Pass | Pass | Pass | Pass | Fail |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Pass | Pass | Pass | Pass | Pass |
| invert_matrix | Fail | Pass | Pass | Fail | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Pass | Pass | Fail | Fail | Fail |
| weighted-least-squares | Fail | Pass | Pass | Pass | Fail |
| lipinski_rule_of_five | Pass | Pass | Pass | Pass | Pass |
| mape | Fail | Fail | Fail | Fail | Pass |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Pass | Pass | Pass | Pass | Pass |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Pass | Fail | Pass | Fail | Fail |
| michaelis | Pass | Pass | Pass | Pass | Pass |
| mol_charge | Pass | Pass | Pass | Pass | Pass |
| net_charge | Pass | Pass | Pass | Pass | Pass |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Pass | Pass | Pass | Pass | Pass |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Pass | Pass | Pass | Pass | Pass |
| pib_1d | Pass | Pass | Pass | Pass | Pass |
| pred_interval | Pass | Pass | Pass | Pass | Pass |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Pass | Pass | Pass | Pass | Pass |
| quantile | Fail | Fail | Fail | Fail | Fail |
| random_walk | Pass | Pass | Fail | Pass | Fail |
| rank | Fail | Pass | Pass | Pass | Fail |
| rank | Pass | Pass | Pass | Pass | Pass |
| remove-water | Fail | Pass | Pass | Pass | Pass |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Pass | Pass | Pass | Pass | Pass |
| rog | Pass | Pass | Pass | Pass | Pass |
| sasa | Fail | Pass | Fail | Fail | Pass |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Pass | Pass | Pass | Pass | Pass |
| seq-trans | Pass | Pass | Pass | Pass | Pass |
| sequence | Pass | Pass | Fail | Pass | Pass |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Fail | Fail | Pass | Pass | Pass |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Fail | Pass | Pass | Pass | Pass |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ["G", "A", "S", "T", "C", "P", "N", "D", "Q", "E", "H", "R", "K", "M", "I", "L", "V", "F", "Y", "W"]:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ["G", "A", "S", "T", "C", "Y", "N", "Q"]:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for amino_acid in sequence:
if amino_acid in ['Q', 'N', 'H', 'S', 'T', 'Y', 'C', 'M']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['S', 'T', 'N', 'Q', 'D', 'E']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
polar_count = 0
for aa in sequence:
if aa in ['Q', 'N', 'H', 'S', 'T', 'Y', 'C', 'M', 'W']:
polar_count += 1
return polar_count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
return T1*(P2/P1)**((gamma-1)/gamma)
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 * (P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
return T1*(P2/P1)**((gamma-1)/gamma)
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1*(P2/P1)**((gamma-1)/gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
# align to the first frame
traj.superpose(traj, frame=frame_index)
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
'NoneType' object has no attribute 'xyz'
angle
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
return np.arccos(np.dot(v1,v2)/(np.linalg.norm(v1)*np.linalg.norm(v2)))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
cos_angle = np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2))
angle = np.arccos(cos_angle)
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
# start
v1_u = v1 / np.linalg.norm(v1)
v2_u = v2 / np.linalg.norm(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_aa:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_aa = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_aa:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic_residues = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic_residues:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
aromatic = ['F', 'Y', 'W']
aromatic_count = 0
for aa in sequence:
if aa in aromatic:
aromatic_count += 1
return aromatic_count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
return k2 * math.exp((Ea/R) * (1/T2 - 1/T1))
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = k2*math.exp((-Ea/8.314)*((1/T2)-(1/T1)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R)*((1/T1) - (1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R) * (1/T2 - 1/T1))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
R = 8.314 # J/mol/K
k1 = k2 * math.exp((Ea/R)*((1/T1)-(1/T2)))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
return k*A*B
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
bb_rad
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.62607004e-34
c = 299792458
k = 1.38064852e-23
return 2*h*c**2/lam**5/(np.exp(h*c/(lam*k*T))-1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
unsupported operand type(s) for -: 'float' and 'NoneType'
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3.0e+8
k = 1.38e-23
return (2*h*c**2/lam**5) / (np.exp(h*c/(lam*k*T)) - 1)
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
h = 6.626e-34
c = 3e8
k = 1.38e-23
return 2*h*c**2/lam**5*(1/(np.exp(h*c/(lam*k*T))-1))
"""
Plot the spectral radiance of a black body at temperature T=6000K, for a range of wavelengths between 0.1 and 10 micrometers.
"""
lam = np.linspace(0.1e-6,10e-6,1000)
plt.plot(lam, bb_radiation(lam, 6000))
plt.xlabel('Wavelength (m)')
plt.ylabel('Spectral radiance (W/m^2/m/sr)')
plt.savefig('bb_radiation.png')
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/?about=P05067'
params = {'query': seq, 'format': 'fasta'}
r = requests.post(url, data=params)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find('pre').text
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
too many values to unpack (expected 2)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
url = 'http://www.uniprot.org/blast/?about=P62158'
payload = {'query': seq, 'format': 'html'}
r = requests.post(url, data=payload)
# 3. Get result
soup = BeautifulSoup(r.text, 'html.parser')
# 4. Parse MSA
msa = soup.find_all('pre')[0].text
# 5. Return a tuple of e score, id of top match
return msa
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
# 2.1. Make a dictionary with the sequences
data = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'BLAST_PROGRAMS': 'blastp',
'PAGE_TYPE': 'BlastSearch',
'SHOW_LINKOUT': 'on',
'LINK_LOC': 'blasttab',
'LINK_NAME': '',
'QUERY_FROM': '',
'QUERY_TO': '',
'FILTER': 'L',
'EXPECT': '10',
'FORMAT_TYPE': 'HTML',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_GI': 'on',
'HITLIST_SIZE': '10',
'ALIGNMENTS': '50',
'DESCRIPTIONS': '100',
'FORMAT_OBJECT': 'Alignment',
'FORMAT_EQ_TEXT': '',
'CMD': 'Put',
'PAGE': 'Nucleotides',
'RID': '',
'SEARCH_RID': '',
'SAVED_RID': '',
'BLAST_SPEC': '',
'FORMAT_ENTREZ_QUERY': '',
'FORMAT_VIEW': '',
'NCBI_QUERY_KEY': '',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'SHOW_LINKOUT': 'on',
'GET_SEQUENCE': 'on',
'SHOW_BLAST_LINK': 'on',
'FORMAT_TYPE': 'HTML',
'FORMAT_MODE': '',
'FORMAT_ORGANISM': '',
'EXPECT': '10',
'FORMAT_NUM_ORG': '10',
'FORMAT_NUM_ALIGNMENTS': '10',
'FORMAT_NUM_DESCRIPTIONS': '10',
'FORMAT_NUM_HITLIST_SIZE': '10',
'FORMAT_NUM_SEARCHED': '10',
'FORMAT_NUM_SHOW_OVERVIEW': '10',
'FORMAT_NUM_SHOW_LINKOUT': '10',
'FORMAT_NUM_GET_SEQUENCE': '10',
'FORMAT_NUM_SHOW_BLAST_LINK': '10',
'FORMAT_NUM_FORMAT_TYPE': '10',
'FORMAT_NUM_FORMAT_MODE': '10',
'FORMAT_NUM_FORMAT_ORGANISM': '10',
'FORMAT_NUM_EXPECT': '10',
'FORMAT_NUM_FORMAT_NUM_ORG': '10',
'FORMAT_NUM_FORMAT_NUM_ALIGNMENTS': '10',
'FORMAT_NUM_FORMAT_NUM_DESCRIPTIONS': '10',
'FORMAT_NUM_FORMAT_NUM_HITLIST_SIZE': '10',
'FORMAT_NUM_FORMAT_NUM_SEARCHED': '10',
'FORMAT_NUM_FORMAT_NUM_SHOW_OVERVIEW': '10',
'FORMAT_NUM_FORMAT_NUM_SHOW_LINKOUT': '10',
'FORMAT_NUM_FORMAT_NUM_GET_SEQUENCE': '10',
'FORMAT_NUM_FORMAT_NUM_SHOW_BLAST_LINK': '10
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
EOL while scanning string literal (<string>, line 90)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
# set up BLAST search
url = 'http://blast.ncbi.nlm.nih.gov/Blast.cgi'
values = {'QUERY': seq,
'PROGRAM': 'blastp',
'DATABASE': 'nr',
'CMD': 'Put',
'PAGE': 'Proteins',
'FILTER': 'L',
'EXPECT': '10',
'HITLIST_SIZE': '1',
'FORMAT_TYPE': 'HTML',
'DESCRIPTIONS': '100',
'ALIGNMENTS': '100',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'FORMAT_EQ_TEXT': 'Score',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_USER_EMAIL': '',
'NCBI_USER': '',
'NCBI_PASSWORD': '',
'NCBI_TOOL': 'blast_python',
'NCBI_SID': '',
'NCBI_RID': '',
'NCBI_RID_DEFAULT': '',
'NCBI_STYLE': '',
'NCBI_BANNER': '',
'ALIGNMENT_VIEW': 'Pairwise',
'ENTREZ_QUERY': '',
'CDD_SEARCH': 'on',
'BLAST_PROGRAMS': 'blastp',
'BLAST_SPEC': '',
'PHI_PATTERN': '',
'BLAST_FILTER': 'L',
'EXPECT_LOW': '',
'EXPECT_HIGH': '',
'WORD_SIZE': '3',
'MATRIX_NAME': 'BLOSUM62',
'GAPCOSTS': '11 1',
'COMPOSITION_BASED_STATISTICS': '0',
'FILTER': 'L',
'MASK_CHAR': '2',
'MASK_COLOR': '1',
'FORMAT_ENTREZ_QUERY': '',
'FORMAT_TYPE': 'HTML',
'DESCRIPTIONS': '100',
'ALIGNMENTS': '100',
'NCBI_GI': 'on',
'SHOW_OVERVIEW': 'on',
'FORMAT_OBJECT': 'Alignment',
'FORMAT_EQ_TEXT': 'Score',
'CLIENT': 'web',
'SERVICE': 'plain',
'NCBI_USER_EMAIL': '',
'NCBI_USER': '',
'NCBI_PASSWORD': '',
'NCBI_TOOL': 'blast_python',
'NCBI_SID': '',
'NCBI_RID': '',
'NCBI_RID_DEFAULT': '',
'NCBI_STYLE': '',
'NCBI_BANNER': '',
'ALIGNMENT_VIEW': 'Pairwise',
'ENTREZ_QUERY': '',
'CDD_SEARCH': 'on',
'BLAST_PROGRAMS': 'blastp',
'BLAST_SPEC': '',
'PHI_PATTERN': '',
'BLAST_FILTER': 'L',
'EXPECT_LOW': '',
'EXPECT_HIGH': '',
'WORD
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
EOL while scanning string literal (<string>, line 101)
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
# 1. import packages
import requests
from bs4 import BeautifulSoup
import numpy as np
# 2. Submit BLAST search with sequences
# 2.1. Set up parameters
url = 'http://www.uniprot.org/blast/'
params = {'QUERY': seq,
'DATABASE': 'uniprotkb',
'FILTER': 'yes',
'FORMAT_TYPE': 'HTML',
'EXPECT': '1e-3',
'PROGRAM': 'blastp',
'CLIENT': 'web',
'SERVICE': 'plain',
'CMD': 'Put'}
# 2.2. Submit request
r = requests.get(url, params=params)
# 2.3. Get result
soup = BeautifulSoup(r.text)
# 2.4. Parse MSA
# 2.4.1. Get table
table = soup.find('table', {'class': 'blast_table'})
# 2.4.2. Get rows
rows = table.find_all('tr')
# 2.4.3. Get data
data = []
for row in rows:
data.append([cell.text for cell in row.find_all('td')])
# 2.4.4. Get e score and id of top match
e_score = float(data[1][2])
id = data[1][1]
# 2.5. Return a tuple of e score, id of top match
return e_score, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
'NoneType' object has no attribute 'find_all'
bravais
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
# start
return "cubic"
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 4
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
if group_number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 17)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonicals = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonicals.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonicals
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
can_smiles = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
can_smiles.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return can_smiles
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canon_list.append(Chem.MolToSmiles(mol, isomericSmiles=True))
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - (T_cold / T_hot)
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - (T_cold / T_hot)
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
return 1 - T_cold / T_hot
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap / 8.314) * (1 / T1 - 1 / T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1/T1 - 1/T2))
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp((HVap * (1 / T1 - 1 / T2)) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
return P1 * math.exp(HVap * (1 / T1 - 1 / T2) / 8.314)
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = True if compare_electronegativity("O","C") else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
return mendeleev.element(element1).electronegativity > mendeleev.element(element2).electronegativity
result = True if compare_electronegativity("O","C") else FalseOutput:
'>' not supported between instances of 'method' and 'method'
condiff_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return x[1:] - x[:-1]
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
# start
diff = np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
return np.diff(x)
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(1, n + 1):
sum += i ** 3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
sum = 0
for i in range(n):
sum += i**3
return sum
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606876e-34
c = 299792458.0
return h / math.sqrt(m * v * v + m * c * c)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458.0
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
c = 299792458
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.62606896e-34
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
h = 6.626068e-34
c = 299792458
return h / (m * v)
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
y = a*x**2 + b*x + c
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
derivative_2deg
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
return 2*a*x + b
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
desc_list = []
for smiles in smiles_list:
m = Chem.MolFromSmiles(smiles)
desc_list.append(calc.CalcDescriptors(m))
return np.array(desc_list)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
X = []
for smiles in smiles_list:
m = Chem.MolFromSmiles(smiles)
descrs = calc.CalcDescriptors(m)
X.append(list(descrs))
return np.array(X)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
# initialize list of descriptors
descriptors = []
# initialize list of SMILES
smiles = []
# initialize list of molecules
molecules = []
# initialize list of hashes
hashes = []
# initialize list of fingerprints
fingerprints = []
# initialize list of fingerprints
fingerprints_binary = []
# initialize list of fingerprints
fingerprints_count = []
# initialize list of fingerprints
fingerprints_count_binary = []
# initialize list of fingerprints
fingerprints_count_binary_sparse = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted = []
# initialize list of fingerprints
fingerprints_count_binary_sparse_tanimoto_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count_sorted_unique_count
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
descriptors = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
descriptors.append(calc.CalcDescriptors(mol))
return np.array(descriptors)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
nms = [x[0] for x in Descriptors._descList]
calc = MoleculeDescriptors.MolecularDescriptorCalculator(nms)
desc_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
desc_list.append(calc.CalcDescriptors(mol))
return np.array(desc_list)
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
# start
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i] * coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i] * coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(len(charges)):
dipole += charges[i]*coordinates[i]
return dipole
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole_moment = np.zeros(3)
for i in range(len(charges)):
dipole_moment += charges[i]*coordinates[i]
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
rdbs = Descriptors.NumRadicalElectrons(mol)
return rdbs
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return 0
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return None
else:
return Descriptors.NumRadicalElectrons(mol)
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Success
eigen-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eigenvalues, eigenvectors = np.linalg.eig(M)
return eigenvalues, eigenvectors
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
eig_val, eig_vec = np.linalg.eig(M)
return eig_val, eig_vec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# 对矩阵M进行特征值分解
w, v = np.linalg.eig(M)
# 对特征值进行排序
idx = w.argsort()[::-1]
w = w[idx]
v = v[:,idx]
return w, v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
# start
eig_vals, eig_vecs = np.linalg.eig(M)
return eig_vals, eig_vecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigval, eigvec = np.linalg.eig(M)
return eigval, eigvec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
# begin
eigvals, eigvecs = np.linalg.eig(M)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
cannot unpack non-iterable NoneType object
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigvals, eigvecs = np.linalg.eig(M)
return eigvals, eigvecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigval, eigvec = np.linalg.eig(M)
return eigval, eigvec
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
eigvals, eigvecs = np.linalg.eig(M)
return eigvals, eigvecs
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
element = mendeleev.element(element_symbol)
return element.mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
Success
element_name
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
element = mendeleev.element(element_number)
return element.symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
return mendeleev.element(element_number).symbol
result = True if symbol(26).lower()=="fe" else FalseOutput:
Success
energy_of_e
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
energy = -13.6 * (1 / (n**2))
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
return -13.6 / n**2
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
e = 1.60217662e-19 # electron charge in Coulombs
h = 6.62607004e-34 # Planck's constant in J s
c = 299792458 # speed of light in m/s
R = 10973731.568508 # Rydberg constant in 1/m
return -13.6 * e * (1 - 1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
return -13.6 * (1 / n ** 2)
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
# start
energy = -13.6 * (1 / (n ** 2))
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
must be real number, not NoneType
find_indices
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
# load pdb file
traj = md.load(pdb_file)
# get the indices of first two alpha carbon atoms
ca_indices = [a.index for a in traj.topology.atoms if a.name == 'CA'][:2]
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load_pdb(pdb_file)
ca_indices = pdb.topology.select('name CA')
return ca_indices[0:2]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
traj = md.load(pdb_file)
topology = traj.topology
ca_indices = topology.select('name CA')
return ca_indices[0], ca_indices[1]
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
t = md.load(pdb_file)
ca_indices = []
for i in range(0,2):
ca_indices.append(t.topology.select('name CA and resid ' + str(i+1)))
return ca_indices
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Constant' object has no attribute 'kind'
force_constant
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
k = (1.0/wave_len)*(1.0/wave_len)*(m1*m2)/(m1+m2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# begin
mu = m1*m2/(m1+m2)
k = 4.0*np.pi**2*mu/(wave_len*1.0e-8)**2
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# begin
mu = m1*m2/(m1+m2)
k = (wave_len*100)**2*mu*1.66053886e-27
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# start
mu = m1*m2/(m1+m2)
k = (wave_len*100)**2*mu
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
# begin
k = (m1*m2)/(m1+m2)*(wave_len*1.0e-2)**2
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
fourier_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
return np.fft.fft(x)
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n]*np.exp(-2j*np.pi*k*n/N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=np.complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
X[k] += x[n] * np.exp(-2j * np.pi * k * n / N)
return X
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
freezing_depression
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return Kf * m
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
Success
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find("table", {"class": "matrix"})
rows = table.find_all("tr")
matrices = []
for row in rows:
cols = row.find_all("td")
cols = [ele.text.strip() for ele in cols]
matrices.append([ele for ele in cols if ele])
matrices = np.array(matrices)
matrices = matrices[:, 1:]
matrices = matrices.astype(np.float)
return matrices
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://it.iucr.org/Ac/ch4o3etpDw/sgtable/' + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find_all('table')[0]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://it.iucr.org/Ab/chap4/sgtable4/" + str(gnum) + "/"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
table = soup.find("table", {"class": "sgtable"})
rows = table.findAll("tr")
generators = []
for row in rows:
cells = row.findAll("td")
if len(cells) == 4:
generators.append([cells[1].text, cells[2].text, cells[3].text])
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'findAll'
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = 'http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=' + str(gnum)
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
table = soup.find_all('table')[1]
rows = table.find_all('tr')
generators = []
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
generators.append([ele for ele in cols if ele])
generators = generators[1:]
for i in range(len(generators)):
generators[i] = generators[i][1:]
for i in range(len(generators)):
generators[i] = [float(x) for x in generators[i]]
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
import requests
from bs4 import BeautifulSoup
import numpy as np
"""
print requests version
"""
print(requests.__version__)
# end
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
url = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-geninfo?gnum=" + str(gnum)
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
tables = soup.find_all("table")
generators = []
for table in tables:
if "Generators" in table.text:
rows = table.find_all("tr")
for row in rows:
if "Generators" in row.text:
continue
else:
generators.append(row.text.split())
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
list index out of range
heating_water
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * 4.184 * (T2 - T1)
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return n * (T2 - T1) * 4.184
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'ILE', 'LEU', 'MET', 'PHE', 'PRO', 'TRP', 'VAL']:
hydrophobic_residues.append(residue.index)
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load_pdb(pdb_filename)
# Get list of residues
residues = pdb.topology.residues
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb_file = md.load_pdb(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb_file.topology.residues:
if residue.is_water:
continue
if residue.is_protein:
if residue.name in ['ALA', 'ILE', 'LEU', 'MET', 'PHE', 'PRO', 'TRP', 'VAL']:
hydrophobic_residues.append(residue.index)
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# Load PDB file
pdb = md.load(pdb_filename)
# Get list of hydrophobic residues
hydrophobic_residues = [residue.index for residue in pdb.topology.residues if residue.is_hydrophobic]
# Return list of hydrophobic residues
return hydrophobic_residues
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Residue' object has no attribute 'is_hydrophobic'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
# load pdb file
pdb = md.load_pdb(pdb_filename)
# get list of hydrophobic residues
hydrophobic_residues = []
for residue in pdb.topology.residues:
if residue.is_water:
continue
if residue.name in ['ALA', 'ILE', 'LEU', 'MET', 'PHE', 'PRO', 'TRP', 'VAL']:
hydrophobic_residues.append(residue.index)
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
Success
ideal_gas
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # atm L / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
R = 0.08205746 # L atm / mol K
return n * R * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
k = 1.38e-23 # Boltzmann constant
return n * k * T / V
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return (a/4)*x**4 + (b/3)*x**3 + (c/2)*x**2 + d*x
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
name 'x' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*d**3/4 + b*d**2/3 + c*d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*x**3/3. + b*x**2/2. + c*x + d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
name 'x' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*d**3/4.0 + b*d**2/3.0 + c*d + d
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
return a*(b**2)/2 + b*c + c*d + d**2/2
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
s = 0.5*f(a) + 0.5*f(b)
for i in range(1,n):
s += f(a + i*h)
return h*s
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a)/n
x = np.linspace(a, b, n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b-a)/n
x = np.linspace(a,b,n+1)
y = f(x)
return h*(0.5*y[0] + 0.5*y[-1] + np.sum(y[1:-1]))
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
sum = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
sum += f(a + i * h)
return h * sum
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
h = (b - a) / n
s = 0.5 * f(a) + 0.5 * f(b)
for i in range(1, n):
s += f(a + i * h)
return s * h
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
invert_matrix
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
A_inv = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# start
A_inv = np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return np.linalg.inv(A)
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
return Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC))
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(Chem.MolTo
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
mol = Chem.MolFromSmiles(Chem.MolToSmiles(Chem.MolFromSmiles(IUPAC)))
return Chem.MolToSmiles(mol)
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Python argument types in
rdkit.Chem.rdmolfiles.MolToSmiles(NoneType)
did not match C++ signature:
MolToSmiles(RDKit::ROMol mol, bool isomericSmiles=True, bool kekuleSmiles=False, int rootedAtAtom=-1, bool canonical=True, bool allBondsExplicit=False, bool allHsExplicit=False, bool doRandom=False)
kld
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
kl_loss = np.sum(np.where(true_data != 0, true_data * np.log(true_data / predicted_data), 0))
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
# start
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
langevin_dynamics
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt
v_traj[i+1] = v_traj[i] + (F(x_traj[i])/m - gamma*v_traj[i])*dt + np.sqrt(2*gamma*T*dt)*np.random.normal()
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
v_traj[i+1] = v_traj[i] - (gamma/m)*v_traj[i]*dt + (1/m)*F(x_traj[i])*dt + np.sqrt(2*gamma*T*dt/m)*np.random.normal()
x_traj[i+1] = x_traj[i] + v_traj[i+1]*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt + 0.5*F(x_traj[i])/m*dt**2
v_traj[i+1] = v_traj[i] + 0.5*(F(x_traj[i])/m + F(x_traj[i+1])/m)*dt - gamma*v_traj[i]*dt + np.sqrt(2*gamma*T/m)*np.random.normal(0,1)*np.sqrt(dt)
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(n_steps-1):
x_traj[i+1] = x_traj[i] + v_traj[i]*dt
v_traj[i+1] = v_traj[i] + (F(x_traj[i])/m - gamma*v_traj[i] + np.sqrt(2*gamma*T/m)*np.random.normal())*dt
return x_traj,v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
weighted-least-squares
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
# start
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(np.diag(w)).dot(x)).dot(x.T).dot(np.diag(w)).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
w = np.diag(w)
return np.linalg.inv(x.T.dot(w).dot(x)).dot(x.T).dot(w).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
return np.linalg.inv(x.T.dot(w).dot(x)).dot(x.T).dot(w).dot(y)
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
shapes (3,) and (100,3) not aligned: 3 (dim 0) != 100 (dim 0)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
if mol is None:
return False
else:
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
m = Chem.MolFromSmiles(smiles)
if m is None:
return False
else:
if rdMolDescriptors.CalcNumHBD(m) > 5:
return False
if rdMolDescriptors.CalcNumHBA(m) > 10:
return False
if Descriptors.MolWt(m) > 500:
return False
if Crippen.MolLogP(m) > 5:
return False
return True
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
# create a molecule from the SMILES string
mol = Chem.MolFromSmiles(smiles)
# calculate the number of hydrogen bond donors
hbd = rdMolDescriptors.CalcNumHBD(mol)
# calculate the number of hydrogen bond acceptors
hba = rdMolDescriptors.CalcNumHBA(mol)
# calculate the molecular weight
mw = Descriptors.MolWt(mol)
# calculate the octanol-water partition coefficient
logp = Crippen.MolLogP(mol)
# check if the molecule satisfies Lipinski's rule of five
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
hbd = rdMolDescriptors.CalcNumHBD(mol)
hba = rdMolDescriptors.CalcNumHBA(mol)
mw = Descriptors.MolWt(mol)
logp = Crippen.MolLogP(mol)
if hbd <= 5 and hba <= 10 and mw < 500 and logp < 5:
return True
else:
return False
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
Success
mape
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y_hat)):
mape += abs(y_hat[i] - y[i]) / y[i]
mape /= len(y_hat)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
# start
mape = 0
for i in range(len(y)):
mape += abs(y_hat[i] - y[i]) / y[i]
mape /= len(y)
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
return np.mean(np.abs((y-y_hat)/y))*100
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
Success
mapping_operator
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# get the number of atoms
n_atoms = molecule.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# loop over the beads
for bead_index, bead_selection in enumerate(beads_mappings):
# get the masses
masses = molecule.select_atoms(bead_selection).masses
# get the number of atoms in the bead
n_bead_atoms = len(masses)
# get the total mass of the bead
total_mass = np.sum(masses)
# get the mass-mass weighted mapping
mass_mass_weighted_mapping = masses / total_mass
# get the indices of the atoms in the bead
atom_indices = molecule.select_atoms(bead_selection).indices
# set the mapping matrix
mapping_matrix[bead_index, atom_indices] = mass_mass_weighted_mapping
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'replace'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Get the number of beads
n_beads = len(beads_mappings)
# Get the number of atoms
n_atoms = molecule.n_atoms
# Create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms), dtype=np.float64)
# Loop over the beads
for bead_index in range(n_beads):
# Get the bead
bead = beads_mappings[bead_index]
# Get the atoms
atoms = bead.atoms
# Get the masses
masses = atoms.masses
# Get the number of atoms
n_atoms = len(atoms)
# Loop over the atoms
for atom_index in range(n_atoms):
# Get the atom
atom = atoms[atom_index]
# Get the mass
mass = masses[atom_index]
# Get the atom index
atom_index = atom.index
# Set the mapping matrix
mapping_matrix[bead_index, atom_index] = mass
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'atoms'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
nbeads = len(beads_mappings)
# get the number of atoms
natoms = molecule.atoms.n_atoms
# create the mapping matrix
mapping_matrix = np.zeros((nbeads, natoms))
# loop over the beads
for i, bead_mapping in enumerate(beads_mappings):
# get the indices of the atoms in the bead
indices = bead_mapping.indices
# get the masses of the atoms in the bead
masses = bead_mapping.masses
# normalize the masses
masses = masses / masses.sum()
# set the mapping matrix
mapping_matrix[i, indices] = masses
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# get the number of beads
n_beads = len(beads_mappings)
# create the mapping matrix
mapping_matrix = np.zeros((n_beads, molecule.n_atoms))
# loop over the beads
for bead_index, bead_selection in enumerate(beads_mappings):
# get the mass-weighted average position of the bead
bead_mass_weighted_position = np.average(molecule.atoms.positions, weights=molecule.atoms.masses, axis=0)
# get the distances between the bead and all atoms
distances = np.linalg.norm(molecule.atoms.positions - bead_mass_weighted_position, axis=1)
# get the indices of the atoms closest to the bead
closest_atoms_indices = np.argsort(distances)[:bead_selection]
# set the mapping matrix
mapping_matrix[bead_index, closest_atoms_indices] = 1.0
# return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
slice indices must be integers or None or have an __index__ method
import MDAnalysis
import numpy as np
"""
Print version string
"""
print(MDAnalysis.__version__)
# end
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
# Get the number of beads
n_beads = len(beads_mappings)
# Get the number of atoms
n_atoms = molecule.n_atoms
# Create the mapping matrix
mapping_matrix = np.zeros((n_beads, n_atoms))
# Loop over the beads
for i, bead_mapping in enumerate(beads_mappings):
# Get the indices of the atoms in the bead
indices = bead_mapping.indices
# Get the masses of the atoms in the bead
masses = bead_mapping.masses
# Get the total mass of the bead
total_mass = masses.sum()
# Get the mass-mass weighted mapping
mass_mass_weighted_mapping = masses / total_mass
# Set the mapping matrix
mapping_matrix[i, indices] = mass_mass_weighted_mapping
# Return the mapping matrix
return mapping_matrix
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'indices'
matpow
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.eye(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(np.dot(x,x),n/2)
else:
return np.dot(x,matpow(np.dot(x,x),(n-1)/2))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
else:
return np.dot(x,matpow(x,n-1))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(x.dot(x), n/2)
else:
return x.dot(matpow(x, n-1))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
else:
return np.dot(x,matpow(x,n-1))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
if n == 0:
return np.identity(x.shape[0])
elif n == 1:
return x
elif n % 2 == 0:
return matpow(np.dot(x,x),n/2)
else:
return np.dot(x,matpow(np.dot(x,x),(n-1)/2))
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n-1)
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n-1)
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n.all() < 0:
return "Error"
else:
return np.prod(np.arange(1,n+1))
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
max-boltz
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann's constant
return math.sqrt(k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806488e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # J/K
return math.sqrt(k*T/M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
k = 1.3806503e-23 # Boltzmann constant in J/K
return math.sqrt(k * T / M)
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
Success
michaelis
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
return Vmax * S / (Km + S)
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
return Chem.GetFormalCharge(mol)
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
# start
charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
charge += 1
elif aa == 'D' or aa == 'E':
charge -= 1
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
net_charge = 0
for aa in sequence:
if aa == 'K' or aa == 'R':
net_charge += 1
elif aa == 'D' or aa == 'E':
net_charge -= 1
return net_charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0,:] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h*fn(t[i], y[i,:])
k2 = h*fn(t[i] + h/4, y[i,:] + k1/4)
k3 = h*fn(t[i] + 3*h/8, y[i,:] + 3*k1/32 + 9*k2/32)
k4 = h*fn(t[i] + 12*h/13, y[i,:] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h*fn(t[i] + h, y[i,:] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h*fn(t[i] + h/2, y[i,:] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = h * fn(t[i], y[i])
k2 = h * fn(t[i] + h/4, y[i] + k1/4)
k3 = h * fn(t[i] + 3*h/8, y[i] + 3*k1/32 + 9*k2/32)
k4 = h * fn(t[i] + 12*h/13, y[i] + 1932*k1/2197 - 7200*k2/2197 + 7296*k3/2197)
k5 = h * fn(t[i] + h, y[i] + 439*k1/216 - 8*k2 + 3680*k3/513 - 845*k4/4104)
k6 = h * fn(t[i] + h/2, y[i] - 8*k1/27 + 2*k2 - 3544*k3/2565 + 1859*k4/4104 - 11*k5/40)
y[i+1] = y[i] + 25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t),len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1]-t[i]
k1 = h*fn(t[i],y[i])
k2 = h*fn(t[i]+h/4,y[i]+k1/4)
k3 = h*fn(t[i]+3*h/8,y[i]+3*k1/32+9*k2/32)
k4 = h*fn(t[i]+12*h/13,y[i]+1932*k1/2197-7200*k2/2197+7296*k3/2197)
k5 = h*fn(t[i]+h,y[i]+439*k1/216-8*k2+3680*k3/513-845*k4/4104)
k6 = h*fn(t[i]+h/2,y[i]-8*k1/27+2*k2-3544*k3/2565+1859*k4/4104-11*k5/40)
y[i+1] = y[i] + 25*k1/216+1408*k3/2565+2197*k4/4104-k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t), len(y0)))
y[0] = y0
for i in range(len(t)-1):
h = t[i+1] - t[i]
k1 = fn(t[i], y[i])
k2 = fn(t[i] + h/4, y[i] + h/4*k1)
k3 = fn(t[i] + 3*h/8, y[i] + 3*h/32*k1 + 9*h/32*k2)
k4 = fn(t[i] + 12*h/13, y[i] + 1932*h/2197*k1 - 7200*h/2197*k2 + 7296*h/2197*k3)
k5 = fn(t[i] + h, y[i] + 439*h/216*k1 - 8*h*k2 + 3680*h/513*k3 - 845*h/4104*k4)
k6 = fn(t[i] + h/2, y[i] - 8*h/27*k1 + 2*h*k2 - 3544*h/2565*k3 + 1859*h/4104*k4 - 11*h/40*k5)
y[i+1] = y[i] + h/6*(25*k1/216 + 1408*k3/2565 + 2197*k4/4104 - k5/5)
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
y = np.zeros((len(t),len(y0)))
y[0,:] = y0
for i in range(len(t)-1):
h = t[i+1]-t[i]
k1 = h*fn(t[i],y[i,:])
k2 = h*fn(t[i]+h/4,y[i,:]+k1/4)
k3 = h*fn(t[i]+3*h/8,y[i,:]+3*k1/32+9*k2/32)
k4 = h*fn(t[i]+12*h/13,y[i,:]+1932*k1/2197-7200*k2/2197+7296*k3/2197)
k5 = h*fn(t[i]+h,y[i,:]+439*k1/216-8*k2+3680*k3/513-845*k4/4104)
k6 = h*fn(t[i]+h/2,y[i,:]-8*k1/27+2*k2-3544*k3/2565+1859*k4/4104-11*k5/40)
y[i+1,:] = y[i,:] + 25*k1/216+1408*k3/2565+2197*k4/4104-k5/5
return y
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
ohe
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
# raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# start
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# start
ohe = np.zeros((len(a), len(set(a))))
for i in range(len(a)):
ohe[i, a[i]] = 1
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
b = np.zeros((len(a),len(set(a))))
for i in range(len(a)):
b[i,a[i]] = 1
return b
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
# YOUR CODE HERE
#raise NotImplementedError()
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
osmotic_pressure
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi/(R*T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / R / T
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
return Pi / (R * T)
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
pair_wise
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
traj.atom_slice(traj.topology.select('name CA'), inplace=True)
# 3
n_pairs = traj.n_atoms * (traj.n_atoms - 1) / 2
# 4
return md.compute_distances(traj, np.triu_indices(traj.n_atoms, 1))
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
traj.atom_slice(traj.topology.select('name CA'), inplace=True)
# 3
pairs = traj.topology.select_pairs('name CA', 'name CA')
# 4
distances = md.compute_distances(traj, pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
topology = traj.topology
alpha_carbons = topology.select('name CA')
# 3
pairs = list(itertools.combinations(alpha_carbons, 2))
# 4
distances = md.compute_distances(traj, pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# 1
traj = md.load(pdb_file)
# 2
alpha_carbons = traj.topology.select('name CA')
# 3
alpha_pairs = list(itertools.combinations(alpha_carbons, 2))
# 4
distances = md.compute_distances(traj, alpha_pairs)
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
# Load pdb file
traj = md.load(pdb_file)
# Select only the alpha carbons
alpha_carbons = traj.topology.select('name CA')
# Calculate the number of unique alpha carbon pairs
num_pairs = len(alpha_carbons) * (len(alpha_carbons) - 1) / 2
# Calculate the distances between each alpha carbon pair
distances = md.compute_distances(traj, alpha_carbons, alpha_carbons)
# Return the distances between each alpha carbon pair
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
ninside = 0
for i in range(nsamples):
x = np.random.uniform(0,1)
y = np.random.uniform(0,1)
if x**2 + y**2 < 1:
ninside += 1
return 4*ninside/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4.0*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4.0*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4*np.sum(r<1)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
x = np.random.uniform(0,1,nsamples)
y = np.random.uniform(0,1,nsamples)
r = np.sqrt(x**2 + y**2)
return 4.0*np.sum(r<1.0)/nsamples
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
pib_1d
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n*n*math.pi*math.pi*hbar*hbar)/(2*m*L*L)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return n**2 * math.pi**2 * hbar**2 / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return n**2 * math.pi**2 * hbar**2 / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
return (n**2 * math.pi**2 * hbar**2) / (2 * m * L**2)
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
Success
pred_interval
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return int(np.ceil(np.log(1-pred_level)/np.log(1-p)))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
return np.ceil(np.log(1-pred_level)/np.log(1-p))
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split()
cids = ",".join(cids)
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % cids
response = requests.get(url)
return set(response.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles)
cids = r.text.split()
r = requests.get('https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % ','.join(cids))
return set(r.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
r = requests.get(url)
cids = r.text.split()
cids = ','.join(cids)
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % cids
r = requests.get(url)
return r.text.split()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem API request
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT' % smiles
r = requests.get(url)
# Parse the response
cids = r.text.split()
# PubChem API request
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT' % ','.join(cids)
r = requests.get(url)
# Parse the response
return set(r.text.split())
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/%s/cids/TXT" % smiles
response = requests.get(url)
cids = response.text.split()
# PubChem REST API
url = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/%s/property/CanonicalSMILES/TXT" % ",".join(cids)
response = requests.get(url)
return response.text.split()
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
pyscf_energy
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
# Create molecule object
mol = pyscf.gto.Mole()
# Add atom
mol.atom = atom
# Set basis
mol.basis = basis
# Set charge and spin multiplicity
mol.charge = 0
mol.spin = 0
mol.build()
# Create RHF object
hf = pyscf.scf.RHF(mol)
# Run SCF
hf.kernel()
# Return energy
return hf.energy_tot()
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.kernel()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
"""
Print pyscf version string
"""
print(pyscf.__version__)
# end
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.Mole()
mol.atom = atom
mol.basis = basis
mol.build()
mf = pyscf.scf.RHF(mol)
mf.scf()
return mf.e_tot
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
return Descriptors.qed(mol)
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
Success
quantile
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# begin
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q*100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
a = np.sort(a)
q = np.array(q)
return a[np.floor(q*len(a)).astype(int)]
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
# start
return np.percentile(a, q * 100)
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
operands could not be broadcast together with shapes (300,) (3,)
random_walk
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N+1)
x[0] = x0
for i in range(N):
x[i+1] = x[i] + a*np.random.choice([-1,1])
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Timeout
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
x[0] = x0
for i in range(1,N):
x[i] = x[i-1] + a*(2*np.random.randint(2) - 1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
x = np.zeros(N)
for i in range(N):
x[i] = x0 + a*(2*np.random.randint(2)-1)
return x
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
# 请在这里完成代码
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
# begin
u, s, vh = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
# YOUR CODE HERE
u, s, v = np.linalg.svd(M)
rank = np.sum(s > 1e-10)
# END YOUR CODE
return rank
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
# start
U, s, V = np.linalg.svd(M)
rank = 0
for i in range(len(s)):
if s[i] > 1e-10:
rank += 1
return rank
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
# begin
U, s, V = np.linalg.svd(M)
rank = np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
# start
u, s, v = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
"""
Rank of matrix a
"""
print(rank(a))
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M, full_matrices=True)
return np.sum(s > 1e-10)
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
remove-water
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent()
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file,top=top_file)
traj.remove_solvent(inplace=True)
return traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
Success
rms_velocity
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant in J/K
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38064852e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23
return math.sqrt(3*k*T/m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
k = 1.38e-23 # Boltzmann constant
return math.sqrt(3 * k * T / m)
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean(np.square(a-b)))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
return np.sqrt(np.mean((a-b)**2))
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
return md.compute_rg(traj)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
rgyr = md.compute_rg(traj)
# Return the radius of gyration
return rgyr
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
traj = md.load(pdb_file)
return md.compute_rg(traj)
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
# Load the pdb file
traj = md.load(pdb_file)
# Calculate the radius of gyration
radius_of_gyration = md.compute_rg(traj)
# Return the radius of gyration
return radius_of_gyration
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
Success
sasa
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj)
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj, mode='residue')
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load pdb
traj = md.load(pdb_file)
# Calculate sasa
sasa = md.shrake_rupley(traj)
# Return sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
traj = md.load(pdb_file)
sasa = md.shrake_rupley(traj)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
# Load the pdb
traj = md.load(pdb_file)
# Calculate the sasa
sasa = md.shrake_rupley(traj, mode='residue')
# Return the sasa
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
Success
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmarts(Chem.MolToSmarts(mol))
return Chem.MolToSmiles(scaffold)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol, rootedAtAtom=0, isomericSmiles=False))
core = Chem.DeleteSubstructs(scaffold, Chem.MolFromSmarts('[*]~[*]'))
return Chem.MolToSmiles(core, isomericSmiles=False)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol, True))
core = Chem.DeleteSubstructs(scaffold, Chem.MolFromSmarts('[*]'))
return Chem.MolToSmiles(core)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmiles(Chem.MolToSmiles(mol, True))
core = Chem.DeleteSubstructs(scaffold, Chem.MolFromSmarts('[*]'))
return Chem.MolToSmiles(core)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold = Chem.MolFromSmarts(Chem.MolToSmarts(mol))
return Chem.MolToSmiles(scaffold)
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
return alns[0][0], alns[0][1]
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
return aln_seq1, aln_seq2
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
Success
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
# convert to amino acid sequence
aa_seq = Seq(gene_seq).translate()
return aa_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
"""
print biopython version
"""
print(Bio.__version__)
# end
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
return Seq(gene_seq).translate()
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.logspace(np.log10(s),np.log10(e),l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.logspace(np.log10(s),np.log10(e),l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.linspace(s,e,l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.logspace(np.log10(s),np.log10(e),l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
return np.logspace(np.log10(s),np.log10(e),l)
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
sle
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in eqn.split('+'):
var = var.split('-')[-1].split('=')[0].strip()
if var not in vars:
vars.append(var)
# create a matrix of coefficients
coeffs = []
for eqn in eqns:
coeff = []
for var in vars:
coeff.append(sympy.sympify(eqn.split(var)[0].split('+')[-1].split('-')[-1].strip()))
coeffs.append(coeff)
# create a vector of constants
consts = []
for eqn in eqns:
consts.append(sympy.sympify(eqn.split('=')[-1].strip()))
# solve the system of linear equations
sol = sympy.solve_linear_system(sympy.Matrix(coeffs),*vars)
# return the solution
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse ''' failed, because of exception being raised:
SyntaxError: unexpected EOF while parsing (<string>, line 0)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of symbols
x = sympy.symbols('x:%d' % len(eqns))
# create a list of equations
eqns = [sympy.sympify(eq) for eq in eqns]
# solve the system of equations
sol = sympy.solve(eqns, x)
# return the solution
return sol
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
vars = []
for eqn in eqns:
for var in eqn.split('+'):
if var.split('-')[0].strip() not in vars:
vars.append(var.split('-')[0].strip())
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
# create a list of variables
var_list = []
for eqn in eqns:
for var in eqn.split('+'):
var = var.split('-')[0]
var = var.split('=')[0]
var = var.strip()
if var not in var_list:
var_list.append(var)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
'NoneType' object has no attribute 'values'
import sympy
"""
print sympy version
"""
print(sympy.__version__)
# end
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = [sympy.Eq(eqn) for eqn in eqns]
return sympy.solve(eqns)
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
SympifyError: '4x + 3y = 20'
spectral_r
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_radius = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigenvalues = np.linalg.eigvals(a)
spectral_r = np.max(np.abs(eigenvalues))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
eigvals = np.linalg.eigvals(a)
return np.max(np.abs(eigvals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigvals = np.linalg.eigvals(a)
return max(abs(eigvals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
# start
eigvals = np.linalg.eigvals(a)
return np.max(np.abs(eigvals))
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
find_peaks
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.1)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks,1])[::-1]]
# Return the highest `npeaks` peaks
return peaks[:npeaks]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.1)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks, 1])[::-1]]
# Return the highest `npeaks` peaks
return abs_spectrum[peaks[:npeaks], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find peaks
peaks = scipy.signal.find_peaks(abs_spectrum[:,1], height=0.01)
# Sort by height
peaks = sorted(peaks[0], key=lambda x: abs_spectrum[x, 1], reverse=True)
# Return the wavenumbers of the peaks
return abs_spectrum[peaks[:npeaks], 0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks = scipy.signal.find_peaks_cwt(abs_spectrum[:,1], np.arange(1,10))
peaks = [abs_spectrum[p,0] for p in peaks]
peaks = sorted(peaks, key=lambda x: -x)
return peaks[:npeaks]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
import numpy as np
import scipy
"""
Create matrix of ones
"""
a = np.ones((5,10))
# end
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
# Find the peaks
peaks, _ = scipy.signal.find_peaks(abs_spectrum[:,1], height=0)
# Sort the peaks by height
peaks = peaks[np.argsort(abs_spectrum[peaks,1])[::-1]]
# Return the highest `npeaks` peaks
return abs_spectrum[peaks[:npeaks],0]
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
Success
speed_of_sound
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314
return math.sqrt(gamma*R*T/m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
"""
compute sin(pi/2)
"""
x = math.sin(math.pi / 2)
# end
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
R = 8.314 # J/mol/K
return math.sqrt(gamma * R * T / m)
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a mol object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a query object from the mol object
query = Chem.MolFromSmiles(Chem.MolToSmiles(mol))
# create a list to store the indices of the entries that contain the substructure
indices = []
# loop through mol_list
for i in range(len(mol_list)):
# if the query is in the mol object, add the index to the list
if mol_list[i].HasSubstructMatch(query):
indices.append(i)
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol = Chem.MolFromSmiles(smiles)
matches = []
for i, mol_entry in enumerate(mol_list):
if mol.HasSubstructMatch(mol_entry):
matches.append(i)
return matches
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the molecules that contain the substructure
indices = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure
if mol_list[i].HasSubstructMatch(mol):
# add the index to the indices list
indices.append(i)
# return the indices list
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule object from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list to store the indices of the molecules that contain the substructure
indices = []
# loop through the molecules in mol_list
for i in range(len(mol_list)):
# if the molecule contains the substructure, add the index to the indices list
if mol_list[i].HasSubstructMatch(mol):
indices.append(i)
# return the indices list
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
# create a molecule from the smiles string
mol = Chem.MolFromSmiles(smiles)
# create a list of the indices of the molecules in mol_list that contain the substructure
indices = [i for i, m in enumerate(mol_list) if m.HasSubstructMatch(mol)]
# return the list of indices
return indices
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i+1, len(fps)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j,i] = tanimoto_matrix[i,j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i,j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# generate fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# generate similarity matrix
tanimoto_matrix = np.zeros((len(fps), len(fps)))
for i in range(len(fps)):
for j in range(i, len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
tanimoto_matrix[j, i] = tanimoto_matrix[i, j]
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize empty matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate pairwise Tanimoto similarities
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.TanimotoSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
import numpy as np
"""
print rdkit version
"""
print(rdkit.__version__)
# end
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
# initialize matrix
tanimoto_matrix = np.zeros((len(smiles_list), len(smiles_list)))
# generate ECFP4 fingerprints
fps = [rdMolDescriptors.GetMorganFingerprintAsBitVect(Chem.MolFromSmiles(smile), 2, nBits=bits) for smile in smiles_list]
# calculate pairwise Tanimoto similarity
for i in range(len(fps)):
for j in range(len(fps)):
tanimoto_matrix[i, j] = DataStructs.FingerprintSimilarity(fps[i], fps[j])
return tanimoto_matrix
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
Success
unbdistance
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the index of the ligand
lig_ind = traj.topology.select('resname '+lig_str)
# get the index of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the index of the ligand
lig_ind = traj.topology.select('resname ' + lig_str)
# get the index of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the distance between the two
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_ind = traj.topology.select('resname ' + lig_str)
# get the indices of the protein
prot_ind = traj.topology.select('protein')
# get the center of mass of the ligand
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
# get the center of mass of the protein
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
# get the distance between the two centers of mass
dist = md.compute_distances(traj,lig_com,prot_com)
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
# get the indices of the ligand
lig_indices = traj.topology.select('resname '+lig_str)
# get the indices of the protein
prot_indices = traj.topology.select('protein')
# get the center of mass of the ligand in every frame
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_indices))
# get the center of mass of the protein in every frame
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_indices))
# get the distance between the two centers of mass in every frame
dist = md.compute_distances(traj,lig_com,prot_com)
# return the distance
return dist
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
"""
Print version string
"""
print(md.version.full_version)
# end
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_ind = traj.topology.select('resname '+lig_str)
prot_ind = traj.topology.select('protein')
lig_com = md.compute_center_of_mass(traj.atom_slice(lig_ind))
prot_com = md.compute_center_of_mass(traj.atom_slice(prot_ind))
return md.compute_distances(traj,lig_com,prot_com)
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
T = 0.2
Prompt Override = insert
| Test | Run 0 | Run 1 | Run 2 | Run 3 | Run 4 |
|---|---|---|---|---|---|
| aa_polarity | Fail | Fail | Fail | Fail | Fail |
| adiabatic_expansion | Fail | Fail | Fail | Fail | Fail |
| alignment | Fail | Fail | Fail | Fail | Fail |
| angle | Pass | Pass | Pass | Pass | Pass |
| aromatic_aa | Fail | Fail | Fail | Fail | Fail |
| arrhenius | Fail | Fail | Fail | Fail | Fail |
| bimolecular | Fail | Fail | Pass | Pass | Fail |
| bb_rad | Fail | Fail | Fail | Fail | Fail |
| blast | Fail | Fail | Fail | Fail | Fail |
| bravais | Fail | Fail | Fail | Fail | Fail |
| canonicalize | Pass | Pass | Pass | Pass | Pass |
| carnot_efficiency | Fail | Fail | Fail | Fail | Fail |
| claussius | Fail | Fail | Fail | Fail | Fail |
| compare_electronegativity | Fail | Fail | Fail | Fail | Fail |
| condiff_1d | Pass | Pass | Pass | Pass | Pass |
| cubes | Fail | Fail | Fail | Fail | Fail |
| de_broglie | Pass | Fail | Fail | Fail | Fail |
| derivative1d-ch | Fail | Fail | Fail | Fail | Fail |
| derivative_2deg | Fail | Fail | Fail | Fail | Fail |
| descriptors | Fail | Fail | Fail | Fail | Fail |
| dipole | Fail | Fail | Fail | Fail | Fail |
| dou | Fail | Fail | Fail | Fail | Fail |
| eigen-ch | Fail | Pass | Pass | Pass | Pass |
| eigen | Pass | Pass | Pass | Fail | Pass |
| element_mass | Fail | Fail | Fail | Fail | Fail |
| element_name | Fail | Fail | Fail | Fail | Fail |
| energy_of_e | Fail | Fail | Fail | Fail | Fail |
| find_indices | Fail | Fail | Fail | Fail | Fail |
| force_constant | Fail | Fail | Fail | Fail | Fail |
| fourier_1d | Pass | Fail | Fail | Pass | Fail |
| freezing_depression | Fail | Fail | Fail | Fail | Fail |
| genpos | Fail | Fail | Fail | Fail | Fail |
| heating_water | Fail | Fail | Pass | Fail | Fail |
| hydrophobic_res | Fail | Fail | Fail | Fail | Fail |
| ideal_gas | Fail | Fail | Fail | Fail | Fail |
| integral | Fail | Fail | Fail | Fail | Fail |
| trap | Fail | Fail | Fail | Fail | Fail |
| invert_matrix | Fail | Pass | Fail | Pass | Pass |
| iupac2smiles | Fail | Fail | Fail | Fail | Fail |
| kld | Fail | Fail | Fail | Fail | Fail |
| langevin_dynamics | Fail | Fail | Fail | Fail | Fail |
| weighted-least-squares | Fail | Fail | Fail | Fail | Fail |
| lipinski_rule_of_five | Fail | Fail | Fail | Fail | Fail |
| mape | Fail | Fail | Fail | Fail | Fail |
| mapping_operator | Fail | Fail | Fail | Fail | Fail |
| matpow | Fail | Fail | Fail | Fail | Fail |
| matrix_factorial | Fail | Fail | Fail | Fail | Fail |
| max-boltz | Fail | Fail | Fail | Fail | Fail |
| michaelis | Fail | Fail | Fail | Fail | Fail |
| mol_charge | Pass | Pass | Pass | Pass | Pass |
| net_charge | Fail | Fail | Fail | Fail | Fail |
| solve_ode | Fail | Fail | Fail | Fail | Fail |
| ohe | Fail | Fail | Fail | Fail | Fail |
| osmotic_pressure | Fail | Fail | Fail | Fail | Fail |
| pair_wise | Fail | Fail | Fail | Fail | Fail |
| pi | Fail | Fail | Fail | Fail | Fail |
| pib_1d | Fail | Fail | Fail | Fail | Fail |
| pred_interval | Fail | Fail | Fail | Fail | Fail |
| pubchem | Fail | Fail | Fail | Fail | Fail |
| pyscf_energy | Fail | Fail | Fail | Fail | Fail |
| qed | Fail | Fail | Fail | Fail | Fail |
| quantile | Fail | Fail | Fail | Fail | Fail |
| random_walk | Fail | Fail | Fail | Fail | Fail |
| rank | Fail | Fail | Fail | Fail | Fail |
| rank | Fail | Fail | Fail | Fail | Fail |
| remove-water | Fail | Fail | Fail | Fail | Fail |
| rms_velocity | Fail | Fail | Fail | Fail | Fail |
| rmse | Fail | Fail | Fail | Fail | Fail |
| rog | Fail | Fail | Fail | Fail | Fail |
| sasa | Fail | Fail | Fail | Fail | Fail |
| scaffold | Fail | Fail | Fail | Fail | Fail |
| seq-align | Fail | Fail | Fail | Fail | Fail |
| seq-trans | Fail | Fail | Fail | Fail | Fail |
| sequence | Fail | Fail | Fail | Fail | Fail |
| sle | Fail | Fail | Fail | Fail | Fail |
| spectral_r | Fail | Fail | Fail | Fail | Fail |
| find_peaks | Fail | Fail | Fail | Fail | Fail |
| speed_of_sound | Fail | Fail | Fail | Fail | Fail |
| substructure | Fail | Fail | Fail | Fail | Fail |
| tanimoto | Fail | Fail | Fail | Fail | Fail |
| unbdistance | Fail | Fail | Fail | Fail | Fail |
aa_polarity
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
[insert]
return countimport math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'N':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for x in sequence:
if x == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
import math
import sys
def polar_count(sequence):
"""
This function counts the number of polar uncharged amino acids in the given sequence
"""
count = 0
for char in sequence:
if char == 'P':
count += 1
return count
return count
sample_sequence = "AAAATTVVVVPPPSREREPPII"
result = True if polar_count(sample_sequence) == 3 else FalseOutput:
Success
adiabatic_expansion
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
[insert]
return T2
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + P1*math.exp(-gamma*T1)
T2 = T2 + P2*math.exp(-gamma*T2)
if __name__ == "__main__":
T1 = float(sys.argv[1])
P1 = float(sys.argv[2])
P2 = float(sys.argv[3])
gamma = float(sys.argv[4])
print cooling(T1,P1,P2,gamma)
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*((P2-P1)/(T1-T2))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
local variable 'T2' referenced before assignment
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma*P1*P2*(math.exp((P2-P1)/T1))
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * (P2-P1)
300 else 300
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def cooling(T1,P1,P2,gamma):
"""
This function returns the temperature of an ideal gas expanding adiabatically from P1 to P2
"""
T2 = T1 + gamma * P1
T3 = T2 + gamma * P2
T4 = T3
return T2
import numpy as np
P1 = 1
P2 = 2
T1 = 300
gamma = 5/3
T2 = T1*((P2/P1)**((gamma-1)/gamma))
T2_codex = cooling(T1, P1, P2, gamma)
# check
if np.isclose(T2, T2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
alignment
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
[insert]
return trajimport mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = traj.select([frame_index])
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.select_atoms("resname *" + frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj = md.AlignTraj(traj)
traj = md.AlignTraj(traj, frame_index)
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
expected str, bytes or os.PathLike object, not Trajectory
import mdtraj as md
import numpy as np
def align_traj(traj, frame_index):
"""
This function aligns the given mdtraj trajectory to a specific frame
"""
traj = md.load(traj)
traj.align(frame_index)
|/
return traj
import numpy as np
import sys
import os
import mdtraj as md
pdb_file = os.path.join(_FILE_DIR_, "1VII_twoframe_shifted.pdb")
trj = md.load(pdb_file)
def myrmsd(trj, frame):
xyz = trj.xyz
xyz0 = trj.xyz[frame]
dx = xyz-xyz0
dx2 = (dx*dx).sum(axis=2)
rmsd = np.sqrt(dx2.mean(axis=1))
return rmsd
#print("Starting rmsd:", myrmsd(trj, 0))
aligned_trj = trj.superpose(trj, 0)
my_rmsd = myrmsd(aligned_trj, 0)
#print("Aligned rmsd:", my_rmsd)
nlcc_trj = align_traj(trj, 0)
nlcc_rmsd = myrmsd(nlcc_trj, 0)
#print("nlcc rmsd", nlcc_rmsd)
result = True if np.all(np.abs(my_rmsd - nlcc_rmsd)) < 0.01 else FalseOutput:
invalid syntax (<string>, line 13)
angle
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
[insert]
return angleimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def vector_angle(v1,v2):
"""
This function returns the angle between vector v1 and vector v2.
"""
angle = np.arccos(np.dot(v1,v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
return angle
import numpy as np
def unit_vec(vector):
return vector / np.linalg.norm(vector)
v1 = [1.2,0.5,0.5]
v2 = [-1.5,2.0,0.0]
v1_u = unit_vec(v1)
v2_u = unit_vec(v2)
angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
angle_codex = vector_angle(v1,v2)
if np.isclose(angle, angle_codex) == True:
result = True
else:
result = FalseOutput:
Success
aromatic_aa
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
[insert]
return countimport math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A' or x == 'a':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x == 'A':
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for x in sequence:
if x in "ACGT":
count += 1
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
import math
import sys
def aromatic_aa(sequence):
"""
This function takes in an amino acid sequence and returns the number of aromatic residues there are
"""
count = 0
for letter in sequence:
if letter == 'A':
count += 1
return count
return count
result = True if aromatic_aa("FLRYSCV")==2 else False
Output:
Success
arrhenius
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
[insert]
return k1import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = math.sqrt(T2/T1)
k2 = k1/(math.pow(T1,2)/math.pow(T2,2))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.sqrt(2*math.pi)*Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)*((T2/T1)**2 - Ea**2)
k2 = k1/(T2/T1)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(math.exp((k2/2)/Ea))
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def arrhenius(k2,T2,T1,Ea):
"""
This function returns the value of the rate constant at temperature T1 using the Arrhenius equation
k2 is the rate constant at temperature T2.
Ea is the activation energy in J/mol.
Temperatures are given in Kelvin
"""
k1 = (T2/T1)**(k2/2)
k2 = k1/(1+k1/Ea)
return k1
import numpy as np
# inputs
T1 = 308.18 # in K
T2 = 333.18 # in K
R = 8.314 # J/mol.K
Ea = 108000 # J/mol
k2 = 1e-3 # M-1 s-1
k1 = k2*np.exp((-Ea/R) * (1/T1 - 1/T2))
k1_codex = arrhenius(k2,T2,T1,Ea)
#print(k1,k1_codex)
if np.isclose(k1,k1_codex) == True:
result = True
else:
result = False
Output:
Success
bimolecular
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
[insert]
return rateimport math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = 0
for x in range(0,k):
rate += A*math.pow(B*math.pow(math.log(x/k),2),2)
if __name__ == "__main__":
print bimolecular_rate(2,1,2)
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 17)
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
Success
import math
import sys
def bimolecular_rate(k,A,B):
"""
This function returns the rate of reaction given the rate constant k and concentrations of species A and B
"""
rate = k*A*B
|/
|/
|/
return rate
import numpy as np
k = 2
A = 0.1
B = 0.2
rate = k*A*B
result = True if np.isclose(rate,bimolecular_rate(k,A,B)) else False
Output:
invalid syntax (<string>, line 14)
bb_rad
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
[insert]
return Bimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2)/(lam**2 - T**2 - lam*T)
return B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 - T + lam*T)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 - T**2)
B = np.where(B 0, B + 1e-10, B)
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 12)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T**2) / (lam**2 + T**2)
B = np.sqrt(B/lam)
|/
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def bb_radiation(lam, T):
"""
This function calculates and returns the spectral radiance value in SI unit for wavelength lam at temperature T, using planck's law of black body radiation.
"""
B = (lam**2 - T)/(lam**2 - T + lam*T + lam*T**2)
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
B = B*B
return B
import numpy as np
import matplotlib.pyplot as plt
# input params
h = 6.634e-34 # J.s
c = 3.0e8 # m/s
k = 1.381e-23 # J.K-1
T = 5000 # in K
lamb_val = 1.0e-6 # in m
# spectral radiance
B = (2*h*c**2/lamb_val**5) * (1/(np.exp(h*c/(lamb_val*k*T)) - 1))
print("spectral radiance =", B)
B_codex = bb_radiation(lamb_val, T)
print("spectral radiance from codex =", B_codex)
# check
if abs((B - B_codex) / B) <= 1e-2:
result = True
else:
result = FalseOutput:
Success
blast
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
[insert]
return e, idimport requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq).upper()
seq = str(seq).replace(' ','')
seq = str(seq).replace('\n','')
seq = str(seq).replace('\r','')
seq = str(seq).replace('\t','')
seq = str(seq).replace(',','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
seq = str(seq).replace('"','')
seq = str(seq).replace('\'','')
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
import requests
from bs4 import BeautifulSoup
import numpy as np
def blast(seq):
'''
Returns MSA with a BLAST search. Uses beautiful soup
to parse result.
1. import packages
2. Submit BLAST search with sequences
3. Get result
4. Parse MSA
5. Return a tuple of e score, id of top match
'''
seq = str(seq)
seq = str(seq.upper())
seq = str(seq.lower())
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
seq = str(seq)
return e, id
e, id = blast('>seq1\n'
'PNFYVPFSNATGVVRSPFEYPQYYLAEPWQFSMLAAYMFLLIVLGFPINFLTLYVTVQ')
result = float(e) < 1e-30Output:
name 'e' is not defined
bravais
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
[insert]
return nameimport math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 4
group_number = group_number + 1
group_number = group_number % 8
group_number = group_number + 1
group_number = group_number % 16
group_number = group_number + 1
group_number = group_number % 32
group_number = group_number + 1
group_number = group_number % 64
group_number = group_number + 1
group_number = group_number % 128
group_number = group_number + 1
group_number = group_number % 256
group_number = group_number + 1
group_number = group_number % 512
group_number = group_number + 1
group_number = group_number % 1024
group_number = group_number + 1
group_number = group_number % 2048
group_number = group_number + 1
group_number = group_number % 4096
group_number = group_number + 1
group_number = group_number % 8192
group_number = group_number + 1
group_number = group_number % 16384
group_number = group_number + 1
group_number = group_number % 32768
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = {
0: 'X',
1: 'Y',
2: 'Z',
3: 'A',
4: 'B',
5: 'C',
6: 'D',
7: 'E',
8: 'F',
9: 'G',
10: 'H',
11: 'I',
12: 'J',
13: 'K',
14: 'L',
15: 'M',
16: 'N',
17: 'O',
18: 'P',
19: 'Q',
20: 'R',
21: 'S',
22: 'T',
23: 'U',
24: 'V',
25: 'W',
26: 'X',
27: 'Y',
28: 'Z',
29: 'A',
30: 'B',
31: 'C',
32: 'D',
33: 'E',
34: 'F',
35: 'G',
36: 'H',
37: 'I',
38: 'J',
39: 'K',
40: 'L',
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 54)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
if group_number 1:
raise ValueError("group_number must be greater than 0")
group_number = math.floor(group_number)
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
group_number = group_number % group_number
group_number = group_number + 1
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
invalid syntax (<string>, line 11)
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
lattice = group_number - 1
lattice_letters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
]
lattice_letters_reversed = [
letter[::-1] for letter in lattice_letters
]
lattice_letters_reversed.reverse()
lattice_letters_reversed = "".join(lattice_letters_reversed)
lattice_letters_reversed = lattice_letters_reversed.upper()
lattice_letters_reversed = lattice_letters_reversed.replace("_", "")
lattice_letters_reversed = lattice_letters_reversed.replace("L", "")
lattice_letters_reversed = lattice_letters_reversed.replace("M", "")
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
name 'name' is not defined
import math
import sys
def bravais_lattice(group_number):
"""
Return bravais lattice name given space group number
"""
group_number = int(group_number)
9:
raise ValueError("Invalid group number")
group_number = group_number - 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
group_number = group_number + 1
group_number = group_number % 2
return name
m = bravais_lattice(47)
result = m.lower() == 'orthorhombic'Output:
unindent does not match any outer indentation level (<string>, line 11)
canonicalize
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
[insert]
return canon_listimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canonical_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_list.append(Chem.MolToSmiles(mol))
return canonical_list
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smiles in smiles_list:
mol = Chem.MolFromSmiles(smiles)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def canonical(smiles_list):
"""
Returns list of canonical forms of given molecules
"""
canon_list = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
canonical_smiles = Chem.MolToSmiles(mol, canonical=True)
canon_list.append(canonical_smiles)
return canon_list
smiles = [
'C1=CC=CN=C1',
'c1cccnc1',
'C([H])C'
]
ref_csmiles = [
'c1ccncc1',
'c1ccncc1',
'CC'
]
csmiles = canonical(smiles)
print(csmiles)
print(ref_csmiles)
result = True
for r, c in zip(ref_csmiles, csmiles):
result = result and r == cOutput:
Success
carnot_efficiency
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
[insert]
return eps
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
1:
eps = eps
if eps 1:
eps = 1
return eps
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_cold) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.pow(T_hot / T_cold, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = T_hot / T_cold
eps = math.pow(eps, 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def carnot_efficiency(T_hot, T_cold):
"""
This function returns the efficiency of a carnot efficiency operating between two temperatures
"""
eps = math.sqrt((T_hot / T_cold) ** 2 + (T_hot / T_hot) ** 2)
return eps
import numpy as np
T_cold = 300
T_hot = 600
eps = 1 - T_cold/T_hot
eps_codex = carnot_efficiency(T_hot, T_cold)
# check
if np.isclose(eps, eps_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
claussius
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
[insert]
return P2
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = HVap*T2/(T1+T2)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1/(HVap*T2)
P2 = P2*(T2-T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + (HVap - T1) * (T2 - T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def claussius(HVap, T1, P1, T2):
"""
This function returns the phase transition pressure at temperature T2 given a heat of vaporization HVap, and and reference temperature and pressure T1 and P1
"""
P2 = P1 + HVap * math.exp(-(T2 - T1)/T1)
return P2
import numpy as np
# input
hvap = 5000 #J/mol
P1 = 1 # atm
R = 8.314 # 8.314 J/k mol
T1 = 300 # in K
T2 = 350
P2_codex = claussius(hvap, T1, P1, T2)
P2 = P1*np.exp(-hvap/R*(1/T2-1/T1))
# check
if np.isclose(P2, P2_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
compare_electronegativity
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
[insert]
return resultimport math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.Electronegativity(element1)
result = False
electronegativity:
result = True
else:
result = False
return result
if __name__ == "__main__":
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
print compare_electronegativity("C","C")
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 12)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
mendeleev.electronegativity(element2,element1)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
electronegativity = mendeleev.electronegativity(element1,element2)
0.0:
return True
else:
return False
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
unindent does not match any outer indentation level (<string>, line 11)
import math
import sys
def compare_electronegativity(element1,element2):
"""
This function returns True if element1 has a larger Pauling electronegativity than element2
"""
import mendeleev
result = mendeleev.compare(element1,element2)
return result
result = True if compare_electronegativity("O","C") else FalseOutput:
module 'mendeleev' has no attribute 'compare'
condiff_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
[insert]
return diffimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def condiff_1d(x):
"""
This function computes the difference between consecutive elements in array x.
"""
diff = np.diff(x)
return diff
import numpy as np
x = np.array([1, 2, 4, 7, 0])
true_y = np.ediff1d(x)
pred_y = condiff_1d(x)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
cubes
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
[insert]
return simport math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n * n * n
for i in range(1, n+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, int(math.sqrt(n))+1):
s += i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(2, int(math.sqrt(n))+1):
s *= i
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
import math
import sys
def sum_of_cubes(n):
"""
This function returns the sum of the first n cubes
"""
s = n
for i in range(1, n+1):
s *= i
return s
return s
result = True if sum_of_cubes(5) == 225 else FalseOutput:
Success
de_broglie
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
[insert]
return limport math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l = m*math.pow(10,-(v/10))
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 16)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
|/
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def de_broglie(m,v):
"""
This function returns the de Broglie wavelength for a particle of mass m with speed v.
"""
l=math.sqrt(m*m+v*v)
return l
import numpy as np
# input params
h = 6.626e-34
v = 1.00e6
m = 9.11e-31
lam = h/(m*v)
print("lam =", lam)
lam_codex = de_broglie(m,v)
# check
if np.isclose(lam, lam_codex) == True:
result = True
else:
result = False
Output:
Success
derivative1d-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
[insert]
return dimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/c
dy=(b-a)/c
dx=dx/x
dy=dy/x
return dx,dy
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/c
dy=(b-a)/c
dz=(b-a)/c
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)/(c*x)
dy=(b-a)/(c*x)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)
dy=(c-x)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
这个函数通过生成含有参数a,b,c的二阶多項式来计算x处的一阶导数。
"""
dx=(b-a)
dy=(c-x)
return d
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'd' is not defined
derivative_2deg
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
[insert]
return derivimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,y,2))
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
name 'y' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_derivative(a,b,c,x):
"""
This function generates a 2nd degree polynomial with coefficients a,b,c and return derivative at x
"""
deriv = np.poly1d(np.polyfit(x,a,2))
deriv2 = deriv(x)
return deriv
import numpy as np
result = True if find_derivative(1,2,3,2) == 6 else False Output:
expected 1D vector for x
descriptors
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
[insert]
return descriptorsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=3, nBits=2048))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(Descriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mol))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
module 'rdkit.Chem.Descriptors' has no attribute 'MolDescriptors'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import numpy as np
def get_descriptors(smiles_list):
"""
Returns an N x 8 matrix of descriptors for given SMILEs
"""
descriptors = []
for smi in smiles_list:
mol = Chem.MolFromSmiles(smi)
descriptors.append(rdMolDescriptors.GetMorganFingerprintAsBitVect(mol, radius=4, useFeatures=False))
return descriptors
s = ['CC=O', 'CC=C=C(C(=O)N)']
v = get_descriptors(s)
result = True if np.shape(v) == (2, 8) else FalseOutput:
Success
dipole
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
[insert]
return dipole_momentimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros((len(coordinates), len(charges)))
for i in range(len(coordinates)):
for j in range(len(charges)):
dipole[i][j] = charges[i] - charges[j]
return dipole
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(3):
dipole[i] = charges[i] * np.sum(coordinates[:,i])
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
unsupported operand type(s) for -: 'float' and 'function'
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', coordinates, coordinates)
dipole = dipole / np.sqrt(np.sum(dipole**2))
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 14)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
dipole = np.zeros(3)
for i in range(3):
dipole[i] = np.sum(charges[i,:]*coordinates[:,i])
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
too many indices for array: array is 1-dimensional, but 2 were indexed
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def dipole_moment(coordinates, charges):
"""
This function returns the dipole moment of a molecule
Coordinates is a numpy array of size Nx3
Charges is a numpy array of size N
"""
i', charges, coordinates)
return dipole_moment
import numpy as np
import os
coordinates = np.loadtxt(os.path.join(_FILE_DIR_,"water.xyz"),usecols=(1,2,3))
#note, these are fake
charges = np.loadtxt(os.path.join(_FILE_DIR_,"charges.txt"))
my_dipole = (coordinates.T*charges).sum(axis=1)
nl_dipole = dipole_moment(coordinates,charges)
#print("My result:",my_dipole)
#print("NL result:",nl_dipole)
result = True if np.all(np.abs( my_dipole - nl_dipole )<0.01) else FalseOutput:
EOL while scanning string literal (<string>, line 14)
dou
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
[insert]
return dimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx() not in [b.GetEndAtomIdx(), b.GetBeginAtomIdx()+1]]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bonds = [b for b in bonds if b.GetBeginAtomIdx() == b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.SINGLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.DOUBLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.TRIPLE]
bonds = [b for b in bonds if b.GetBeginAtomIdx()!= b.GetEndAtomIdx()]
bonds = [b for b in bonds if b.GetBondType() == Chem.rdchem.BondType.AROMATIC]
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
name 'd' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def calc_rdbs(smiles):
"""
Return degrees of unsaturation (Double Bond Equivalent) from C, N, H, Halogen count.
"""
mol = Chem.MolFromSmiles(smiles)
bonds = mol.GetBonds()
bondCount = len(bonds)
bondHash = rdMolHash.MolHash(bonds)
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
bondHash.UpdatePropertyCache()
return d
d = calc_rdbs('c1ccccc1')
print('d = ', d)
result = d == 4Output:
Python argument types in
rdkit.Chem.rdMolHash.MolHash(_ROBondSeq)
did not match C++ signature:
MolHash(RDKit::ROMol mol, RDKit::MolHash::HashFunction func)
eigen-ch
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
[insert]
return w,vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
|/
|/
|/
|/
|/
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 18)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
该函数返回矩阵M的特征值和特征向量。
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
eigen
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
[insert]
return w,vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
|/
|/
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
invalid syntax (<string>, line 16)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def eigen(M):
"""
Return eigenvalues and eigenvectors for a square matrix M
"""
w, v = np.linalg.eig(M)
return w,v
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
w, v = np.linalg.eig(M)
w1, v1 = eigen(M)
result = True if np.allclose(w, w1) and np.allclose(v,v1) else FalseOutput:
Success
element_mass
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
[insert]
return massimport math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.elements.get_mass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev.elements' has no attribute 'get_mass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
import math
import sys
def element_mass(element_symbol):
"""
This function returns the mass of the chemical element given by its symbol
"""
import mendeleev
mass = mendeleev.ElementMass(element_symbol)
return mass
import numpy as np
result = True if np.abs(element_mass("U")-238.03)<0.01 else FalseOutput:
module 'mendeleev' has no attribute 'ElementMass'
element_name
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
[insert]
return simport math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
module 'mendeleev' has no attribute 'symbol'
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def symbol(element_number):
"""
This function returns the two letter symbol for the chemical element given by element_number
"""
import mendeleev
s = mendeleev.symbol(element_number)
|/
return s
result = True if symbol(26).lower()=="fe" else FalseOutput:
invalid syntax (<string>, line 13)
energy_of_e
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
[insert]
return energyimport math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.0
for i in range(1,n+1):
energy += i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 1
for i in range(1, n+1):
energy *= i
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = n * (n + 1)
energy -= n * n * n * n * n
energy -= n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
energy -= n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n * n
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (i-1) * (i-2) * (i-3) * (i-4) * (i-5) * (i-6) * (i-7) * (i-8) * (i-9) * (i-10) * (i-11) * (i-12) * (i-13) * (i-14) * (i-15) * (i-16) * (i-17) * (i-18) * (i-19) * (i-20) * (i-21) * (i-22) * (i-23) * (i-24) * (i-25) * (i-26) * (i-27) * (i-28) * (i-29) * (i-30)
return energy
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
Success
import math
import sys
def energy_of_e(n):
"""
This function calculates the energy in electron Volts of an electron in state n in a hydrogen atom
"""
energy = 0.
for i in range(1, int(math.sqrt(n))+1):
energy += i * (n**i)
if __name__ == "__main__":
n = int(sys.argv[1])
energy = energy_of_e(n)
print(energy)
return energy
import math
Rh = 13.60648962
n = 3
energy_true = (-Rh/(n**2))
energy_nlcc = energy_of_e(n)
result = math.isclose(energy_true, energy_nlcc, rel_tol =1e-3)
Output:
'return' outside function (<string>, line 21)
find_indices
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
[insert]
return idximport mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.resname!= 'CA')[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
idx = np.where(atoms.select('CA') == True)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def get_ca_indices(pdb_file):
"""
This function uploads a pdb file and find out the indices of first two alpha carbon atoms.
"""
pdb = md.load(pdb_file)
atoms = pdb.select('CA')
0)[0]
return idx
import os
import numpy as np
pdb_file = os.path.join(_FILE_DIR_,"1l2y.pdb")
def get_pair_indices(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
top = pdb.topology
CAs = [atom.index for atom in top.atoms if atom.name == 'CA']
indices_pair = np.array([CAs[0], CAs[1]])
return indices_pair
my_indices_pair = get_pair_indices(pdb_file)
prompt_indices_pair = get_ca_indices(pdb_file)
result = True if np.all(my_indices_pair == prompt_indices_pair) else False
Output:
unindent does not match any outer indentation level (<string>, line 11)
force_constant
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
[insert]
return kimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1*m2/(wave_len**2)
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def compute_k(m1,m2,wave_len):
"""
Two atom harmonic oscillator.
Returns force constant in kg/s**2 units given masses m1,m2 and wave length
wave_len. Masses are in kg units and wave length in cm^-1 units. Use reduced mass.
"""
k = m1/m2
k = k*wave_len
|/
return k
import numpy as np
m1 = 12.0 #amu
m2 = 16.0 #amu
wave_len = 2100 #1/cm
mass_fac = 1.677e-27 #kg/amu
velocity = 2.99e10 #cm/s
pi = np.pi
mu = (m1*m2)/(m1+m2)*mass_fac
omega = 2*pi*wave_len*velocity
force_const = mu*omega**2
force_const_codex = compute_k(m1,m2,wave_len)
if np.isclose(force_const, force_const_codex) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 17)
fourier_1d
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
[insert]
return wimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.zeros(x.shape[1])
for i in range(x.shape[1]):
w[i] = np.fft.fft(x[:,i])
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
tuple index out of range
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
|/
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.fft.fft(x)
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def fourier_1d(x):
"""
This function returns the one dimensional fourier transform of array x.
"""
w = np.zeros(x.shape[1])
for i in range(x.shape[1]):
w[i] = np.fft.fft(x[:,i])
return w
import numpy as np
from numpy.fft import fft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
true_y = fft(x)
test_y = fourier_1d(x)
result = True if np.allclose(true_y, test_y) else FalseOutput:
tuple index out of range
freezing_depression
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
[insert]
return deltaTimport math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK/math.sqrt(m)
if __name__ == "__main__":
Kf = float(sys.argv[1])
m = float(sys.argv[2])
print freezing_depression(Kf,m)
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT = Kf*m/(Kf+m)
if deltaT 0:
deltaT = 0
else:
deltaT = math.floor(deltaT)
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 12)
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
deltaT=Kf*m
if deltaT0:
deltaT=0
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
name 'deltaT0' is not defined
import math
import sys
def freezing_depression(Kf,m):
"""
This function returns the decrease in freezing point in Kelvin
The depression constant is Kf in K kg/mol and is greater than zero
Molality m is given in mol/kg
"""
KfK = Kf*Kf
deltaT = KfK*m
if deltaT 0:
deltaT = 0
else:
deltaT = deltaT/KfK
return deltaT
return deltaT
import numpy as np
molality = 0.1
depression_constant = -0.512
dT = depression_constant*molality
result = True if np.abs(freezing_depression(depression_constant,molality)-dT)<0.01 else FalseOutput:
invalid syntax (<string>, line 13)
genpos
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
[insert]
return generatorsimport requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for i in range(1,11):
url = "http://www.crystallography.com/spacegroups/" + str(gnum) + "/general-positions.aspx"
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
generators.append([])
for tr in rows:
cols = tr.find_all('td')
generators[i].append([])
for td in cols:
generators[i][-1].append(td.text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
'NoneType' object has no attribute 'find_all'
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = "http://ec.europa.eu/eurostat/eurostat-data/"
page_num = 1
while page_num gnum:
page_url = base_url + str(page_num)
page_response = requests.get(page_url)
page_soup = BeautifulSoup(page_response.text, 'html.parser')
generators.append(page_soup.find_all('table', class_='table')[0])
page_num += 1
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
invalid syntax (<string>, line 16)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1, gnum+1):
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
expected an indented block (<string>, line 13)
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
for g in range(1,11):
generators.append(g*gnum)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
Success
import requests
from bs4 import BeautifulSoup
import numpy as np
def matrix_generators(gnum):
""" Returns list of matrix generators for general positions of given space group
gnum - International Tables for Crystallography space group number
"""
generators = []
base_url = 'http://www.internationalcrystallography.com/crystallography/crystallography/'
soup = BeautifulSoup(requests.get(base_url+str(gnum)).text, 'html.parser')
table = soup.find('table', class_='table')
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
generators.append(cols[0].text)
return generators
import numpy as np
mgs = matrix_generators(66)
ref = np.array([[1, 0, 0, 1/2],
[0, 1, 0, 1/2],
[0, 0, 1, 0]])
result = np.allclose(mgs[-1], ref)Output:
HTTPConnectionPool(host='www.internationalcrystallography.com', port=80): Max retries exceeded with url: /crystallography/crystallography/66 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbfc6272eb0>: Failed to establish a new connection: [Errno -2] Name or service not known'))
heating_water
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
[insert]
return q
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 * math.pow(T2, j))
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = 0.0
for j in range(n):
q += (T1 - T2) * (T1 - T2) / ((T1 - T2) * (T1 - T2))
T1 -= T2
T2 -= T2
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = ((T1-T2)/(n*(n-1))) * math.log(T2/T1)
if __name__ == "__main__":
n = int(sys.argv[1])
T1 = float(sys.argv[2])
T2 = float(sys.argv[3])
print heating_energy(n, T1, T2)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def heating_energy(n, T1, T2):
"""
This function returns the energy in kcal required to heat n moles of water from T1 to T2
"""
q = (T1 * n) / (T2 * n)
return q
import numpy as np
n = 2
T1 = 300
T2 = 350
C = 1*18./1000 #cal/g/deg
q = n*C*(T2-T1)
# heat in kilocalories
q_codex = heating_energy(n, T1, T2)
# check
if np.isclose(q, q_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
hydrophobic_res
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
[insert]
return residsimport mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
expected an indented block (<string>, line 14)
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = md.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'HOH':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
'Trajectory' object has no attribute 'models'
import mdtraj as md
import numpy as np
def get_hydrophobic_residues(pdb_filename):
"""
Returns list of hydrophobic residues indices
"""
pdb = mdtraj.load(pdb_filename)
resids = []
for model in pdb.models:
for residue in model.residues:
if residue.resname!= 'H':
resids.append(residue.index)
return resids
import os
t = md.load(os.path.join(_FILE_DIR_, 'e22g.pdb'))
top = t.topology
hp_res_list = ['ALA', 'VAL', 'LEU', 'ILE', 'PRO', 'PHE', 'CYS']
hydrophobic_res = [res.index for res in top.residues if str(res)[
:3] in hp_res_list]
print(hydrophobic_res)
result = True if get_hydrophobic_residues(os.path.join(
_FILE_DIR_, 'e22g.pdb')) == hydrophobic_res else FalseOutput:
name 'mdtraj' is not defined
ideal_gas
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
[insert]
return Pimport math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n/2)
P = P*1000
if __name__ == "__main__":
n = int(sys.argv[1])
V = float(sys.argv[2])
T = float(sys.argv[3])
P = ideal_gas_pressure(n,V,T)
print P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Missing parentheses in call to 'print'. Did you mean print(P)? (<string>, line 18)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T/(n*math.pow(10,9))
|/ file dstars=0
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 13)
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*math.exp(-T/n)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def ideal_gas_pressure(n,V,T):
"""
This function returns the pressure for n moles of an ideal gas at temperature T and volume V, using the ideal gas equation of state.
The pressure returned is in atm units.
"""
P = V*T*math.exp(-n*T/V)
return P
return P
import numpy as np
# input
V = 20.0 # volume (in L)
n = 10.0 # in moles
R = 0.08206 # in L.atm/mol.K
T = 350 # in K
P = n*R*T/V
#print("Pressure =", P)
codex_pressure = ideal_gas_pressure(n,V,T)
#print("Codex pressure =", codex_pressure)
# check
if np.isclose(P, codex_pressure, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
integral
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
[insert]
return integralimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = 0
for i in range(1,len(a)):
integral += a[i]*(b[i]*c[i] + d[i])
return integral
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
object of type 'int' has no len()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = 0
for i in range(1,len(a)):
integral += a[i]*(b[i]*c[i] + d[i]*b[i]*c[i] + d[i]*b[i]*d[i])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
object of type 'int' has no len()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = a + b + c + d
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def find_integral(a,b,c,d):
"""
This function generates a one dimensional polynomial with coefficients a,b,c,d and returns its integral.
"""
integral = np.poly1d([a,b,c,d])
return integral
import numpy as np
result = True if find_integral(1,2,3,4) == np.poly1d([1/4, 2/3, 3/2, 4, 0]) else False Output:
Success
trap
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
[insert]
return integralimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * (b - a) / i
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * f(b + i * a)
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-b * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += f(a) * np.exp(-(b - a) * i)
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def trap(f, n, a, b):
"""
This function evaluates the integral of a univariate function f from a to b with n itervals using the composite trapezoidal rule.
"""
integral = 0
for i in range(n):
integral += a * (f(a) + f(b) - f(a) + f(b))
a, b = b, a + b
return integral
return integral
import numpy
def f(x):
return x ** 4 * np.log(x + np.sqrt(x ** 2 + 1))
a = 0
b = 5
n = 100
x = np.linspace(a,b,num=n)
test_intgr = np.trapz(f(x), x=x)
result = True if np.isclose(trap(f,n,a,b),test_intgr) else FalseOutput:
loop of ufunc does not support argument 0 of type int which has no callable sqrt method
invert_matrix
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
[insert]
return Ainvimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
name 'Ainv' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
m, n = A.shape
Ainv = np.zeros((m,n))
for i in range(m):
for j in range(n):
Ainv[i,j] = 1/A[i,j]
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
Ainv = np.linalg.inv(A)
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def invert_matrix(A):
"""
This function computes the inverse of matrix A
"""
# Compute the inverse of the matrix
Ainv = np.linalg.inv(A)
# Return the inverse matrix
return Ainv
import numpy as np
x = np.array([[1,-1], [2,6]])
m_i = invert_matrix(x)
x_i = np.array([[0.75,0.125], [-0.25,0.125]])
result = np.array_equal(m_i,x_i)
Output:
Success
iupac2smiles
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
[insert]
return SMILESimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace('-','')
IUPAC = IUPAC.replace('_','')
IUPAC = IUPAC.replace('(','')
IUPAC = IUPAC.replace(')','')
IUPAC = IUPAC.replace(',','')
IUPAC = IUPAC.replace('.','')
IUPAC = IUPAC.replace(';','')
IUPAC = IUPAC.replace(':','')
IUPAC = IUPAC.replace('=','')
IUPAC = IUPAC.replace('!','')
IUPAC = IUPAC.replace('~','')
IUPAC = IUPAC.replace('@','')
IUPAC = IUPAC.replace('#','')
IUPAC = IUPAC.replace('$','')
IUPAC = IUPAC.replace('%','')
IUPAC = IUPAC.replace('^','')
IUPAC = IUPAC.replace('&','')
IUPAC = IUPAC.replace('*','')
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
SMILES = []
for char in IUPAC:
if char.isupper():
SMILES.append(char)
else:
SMILES.append(char.upper())
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(";", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def iupac2smiles(IUPAC):
"""
This function takes in the IUPAC name string and converts it to a SMILES string
"""
IUPAC = IUPAC.upper()
IUPAC = IUPAC.replace("-", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace("(", "")
IUPAC = IUPAC.replace(")", "")
IUPAC = IUPAC.replace("'", "")
IUPAC = IUPAC.replace(":", "")
IUPAC = IUPAC.replace(",", "")
IUPAC = IUPAC.replace("'", "")
return SMILES
iupac = "2,5,5-trimethyl-2-hexene"
smiles = "CC(C)=CCC(C)(C)C"
result = True if iupac2smiles(iupac) == smiles else FalseOutput:
name 'SMILES' is not defined
kld
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
[insert]
return lossimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += np.log(np.linalg.norm(true_data[i] - predicted_data[i]))
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i in range(len(true_data)):
loss += (true_data.data[i]-predicted_data.data[i])**2
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def kld(true_data, predicted_data):
"""
This function calculates the Kullback–Leibler (KL) divergence loss between true_data and predicted_data.
"""
loss = 0
for i, (true_value, predicted_value) in enumerate(zip(true_data, predicted_data)):
loss += (predicted_value - true_value) ** 2
return loss
import numpy as np
np.random.seed(0)
M = 100
targets = np.random.rand(M)
predictions = targets * 0.9
kld_loss = -np.sum(targets*np.log(
np.divide(predictions, targets) + 1e-10))
result = True if np.isclose(kld(targets, predictions), kld_loss) else FalseOutput:
Success
langevin_dynamics
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
[insert]
return x_traj, v_trajimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for t in range(1,n_steps):
x_traj[t] = x_traj[t-1] + dt*F(x_traj[t-1],v_traj[t-1],gamma,T)
v_traj[t] = v_traj[t-1] + dt*F(x_traj[t-1],v_traj[t-1],gamma,T)
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
for i in range(n_steps):
x_traj[i] = x0
v_traj[i] = v0
for j in range(m):
Fx = F(x_traj[i])
Fv = F(v0)
Fx_dot = Fx + gamma*dt*Fv
Fv_dot = Fv + gamma*dt*Fx
x_traj[i] = x_traj[i] + dt*Fx_dot
v_traj[i] = v_traj[i] + dt*Fv_dot
x_traj[i] = x_traj[i] / m
v_traj[i] = v_traj[i] / m
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma,T)
x_traj[-1] = x0
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 4 were given
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
x_traj[0] = x0
v_traj[0] = v0
for i in range(1,n_steps):
x_traj[i] = x_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma)
v_traj[i] = v_traj[i-1] + dt*F(x_traj[i-1],v_traj[i-1],gamma)*m
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
F() takes from 1 to 2 positional arguments but 3 were given
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def run_langevin_dynamics(x0,v0,gamma,F,n_steps,dt=0.003,T=1.0,m=1):
"""
This function runs a Langevin dynamics simulation in 1d in an external potential
It returns the trajectory of x and v.
The initial position is x0
The initial velocity is v0
The temperature is T
m is the mass
F(x) is a function that returns the external force
gamma is the drag coefficient
"""
x_traj = np.zeros(n_steps)
v_traj = np.zeros(n_steps)
for i in range(n_steps):
x_traj[i] = x0
v_traj[i] = v0
x_traj[i+1] = x0 + dt*F(x_traj[i])
v_traj[i+1] = v0 + dt*gamma*F(x_traj[i])
x_traj[i+n_steps] = x0 + dt*F(x_traj[i+n_steps])
v_traj[i+n_steps] = v0 + dt*gamma*F(x_traj[i+n_steps])
x_traj[i+2*n_steps] = x0 + dt*F(x_traj[i+2*n_steps])
v_traj[i+2*n_steps] = v0 + dt*gamma*F(x_traj[i+2*n_steps])
x_traj[i+3*n_steps] = x0 + dt*F(x_traj[i+3*n_steps])
v_traj[i+3*n_steps] = v0 + dt*gamma*F(x_traj[i+3*n_steps])
x_traj[i+4*n_steps] = x0 + dt*F(x_traj[i+4*n_steps])
v_traj[i+4*n_steps] = v0 + dt*gamma*F(x_traj[i+4*n_steps])
x_traj[i+5*n_steps] = x0 + dt*F(x_traj[i+5*n_steps])
return x_traj, v_traj
import numpy as np
import pylab as plt
#def PE(q):
# return (q**2-1.0)**2
#def F(q):
# return -4.0 * q * (q**2-1.0)
def F(q,k=2):
return -k*q
x_traj, v_traj = run_langevin_dynamics(0.1,-0.1,0.1,F,100000)
plt.plot(x_traj)
plt.show()
v_traj_half = np.array(v_traj)[len(v_traj)//2:]
msv = v_traj_half.var()
ideal_msv = 1 #kT/m
result = True if np.abs(msv-ideal_msv)/ideal_msv < 0.2 and np.abs(np.mean(x_traj[len(x_traj)//2:]))<0.1 else FalseOutput:
index 100000 is out of bounds for axis 0 with size 100000
weighted-least-squares
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
[insert]
return betaimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, rcond=None)[0]
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def lsq(x, y, w):
''' Returns fit coefficients from weighted least squares. x should be a matrix.
'''
beta = np.linalg.lstsq(x, y, w)[0]
|/
|/
|/
return beta
import numpy as np
N = 100
x = np.random.randn(N, 3)
beta = np.array([-1.5, 2, -0.5])
y = x @ beta + np.random.randn(N) * 0.01
w = np.random.randn(N) ** 2
w /= np.sum(w)
diag_w = np.zeros((N, N))
np.fill_diagonal(diag_w, w)
# remove bias
y -= np.mean(y)
# compute least squares fit
xtinv = np.linalg.pinv(
x.T @ diag_w @ x
)
beta_hat = xtinv @ x.T @ (y * w)
beta_hat_m = lsq(x, y, w)
result = np.allclose(beta_hat, beta_hat_m)Output:
invalid syntax (<string>, line 13)
lipinski_rule_of_five
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def lipinski_rule_of_five(smiles):
"""
This function calculates the Lipinski descriptors of the given SMILES string and returns a boolean to indicate if Lipinski's rule of five was satisfied.
Lipinski's rules are:
Hydrogen bond donors <= 5
Hydrogen bond acceptors <= 10
Molecular weight < 500 daltons
logP < 5
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol, canonical=True)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
return result
from rdkit import Chem
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
hbd = Chem.rdMolDescriptors.CalcNumHBD(m)
hba = Chem.rdMolDescriptors.CalcNumHBA(m)
wt = Chem.rdMolDescriptors.CalcExactMolWt(m)
logp = Chem.Crippen.MolLogP(m)
if hbd < 5 and hba < 10 and wt < 500 and logp < 5:
passed = True
else:
passed = False
result = True if lipinski_rule_of_five(smiles) == passed else FalseOutput:
name 'result' is not defined
mape
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
[insert]
return eimport math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = math.fabs(y_hat - y)
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = (y_hat-y)/y_hat
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
|/
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 14)
import math
import sys
def mape(y_hat,y):
"""
This function computes the mean absolute percentage error (mape) between y_hat and y.
"""
e = y_hat - y
|/
return e
import numpy as np
np.random.seed(0)
M=100
y_hat = np.random.normal(loc=10,scale=3,size=(M,))
y = np.random.normal(loc=9, scale=2, size=(M,))
test_mape = abs((y - y_hat)*100/ y).mean()
result = True if np.isclose(mape(y_hat,y),test_mape) else FalseOutput:
invalid syntax (<string>, line 16)
mapping_operator
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
[insert]
return Mimport MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for i in range(molecule.n_atoms):
for j in range(molecule.n_atoms):
M[i][j] = beads_mappings[i][j]
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((molecule.n_atoms, molecule.n_atoms))
for bead, bead_mapping in beads_mappings.items():
atom_selection = bead_mapping['atom_selection']
atom_selection_atoms = bead_mapping['atom_selection_atoms']
atom_selection_masses = bead_mapping['atom_selection_masses']
atom_selection_masses = atom_selection_masses[atom_selection]
atom_selection_masses = atom_selection_masses[atom_selection_atoms]
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses * bead_mapping['atom_selection_weight']
atom_selection_masses = atom_selection_masses.sum(axis=0)
atom_selection_masses = atom_selection_masses / np.sum(atom_selection_masses)
atom_selection_masses = atom_selection_masses.reshape((molecule.n_atoms, molecule.n_atoms))
M[atom_selection, atom_selection] = atom_selection_masses
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
'list' object has no attribute 'items'
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i]).GetAtomWithIdx(beads_mappings[j]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(beads_mappings), len(beads_mappings)))
for i in range(len(beads_mappings)):
for j in range(len(beads_mappings)):
M[i][j] = molecule.GetAtomWithIdx(beads_mappings[i][j]).GetAtomWithIdx(beads_mappings[j][i]).GetDegree()
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 16)
import MDAnalysis
import numpy as np
def mapping_operator(molecule, beads_mappings):
"""
This function generates a mass-mass weighted mapping matrix given an MD analysis molecule
and atom selections for the beads.
"""
M = np.zeros((len(molecule), len(molecule)))
for i in range(len(molecule)):
for j in range(len(molecule)):
if beads_mappings[i][j] == 1:
M[i][j] = 1.0
else:
M[i][j] = 0.0
|/
return M
import numpy as np
import MDAnalysis as mda
import os
# read molecule
u = mda.Universe(os.path.join(_FILE_DIR_, 'water.gro'))
molecule = u.atoms
# define atoms that belong to the a single bead
beads_mappings = [['OW', 'HW1', 'HW2']]
Mws_dict = dict(zip(molecule.names, molecule.masses))
M, N = len(beads_mappings), len(molecule)
CG_matrix = np.zeros((M, N))
index = 0
for s in range(M):
for i, atom in enumerate(beads_mappings[s]):
CG_matrix[s, i + index] = [v for k,
v in Mws_dict.items() if atom in k][0]
index += np.count_nonzero(CG_matrix[s])
CG_matrix[s] = CG_matrix[s] / np.sum(CG_matrix[s])
result = True if np.isclose(
CG_matrix, mapping_operator(molecule, beads_mappings)).all() else FalseOutput:
invalid syntax (<string>, line 19)
matpow
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matpow(x,n):
"""
This function computes matrix x raised to the power n.
"""
r = np.power(x,n)
return r
import numpy as np
x = np.array([[0, 1], [-1, 0]])
true_y = np.linalg.matrix_power(x,3)
pred_y = matpow(x,3)
result = True if np.allclose(true_y,pred_y) else FalseOutput:
Success
matrix_factorial
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
[insert]
return fimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.matrix(np.zeros((n,n)))
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.empty([n,n])
for i in range(n):
for j in range(n):
f[i,j] = i**j
return f
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
if n == 0:
return 1
else:
return n * matrix_factorial(n - 1)
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.zeros((n, n))
for i in range(n):
for j in range(n):
f[i, j] = f[j, i] = i
return f
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def matrix_factorial(n):
"""
This function calculates and returns the factorial of a matrix (array) element wise
"""
f = np.empty([n,n])
for i in range(n):
for j in range(n):
f[i,j] = i**j
return f
return f
import numpy as np
x = np.array([[1, 2, 3], [4,5,6]])
m_f = matrix_factorial(x)
x_f = np.array([[1, 2, 6], [24,120,720]])
result = np.array_equal(x_f,m_f)
Output:
only integer scalar arrays can be converted to a scalar index
max-boltz
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
[insert]
return simport math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T/M)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(T*M/1000)
|/
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
import math
import sys
def max_boltz_rms_speed(T,M):
"""
This function returns the rms speed of a molecule in m/s
The temperature is T in Kelvin
The molecule has mass M in kiolograms
"""
s = math.sqrt(M*T/1000)
|/s
return s
import numpy as np
# input params
M = 32e-3 # for O2, kg/mol
R = 8.314 # J/mol.K
T = 300
c_rms = np.sqrt(3.0*R*T/M)
#print("rms speeds :", c_rms)
M_in_kg = M/6.022e23
c_rms_codex = max_boltz_rms_speed(T,M_in_kg)
#print("rms speeds from codex :", c_rms_codex)
# check
if np.isclose(c_rms,c_rms_codex,rtol=0.01):
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 15)
michaelis
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
[insert]
return v
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax
for t in range(S-1):
v = v * math.exp(-t/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * math.exp(-S/Km)
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax/S
v:
v = Km
else:
v = Km
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
unindent does not match any outer indentation level (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * math.exp(-Km * S)
if v 0.1:
v = 0.1
return v
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 10)
import math
import sys
def reaction_velocity(Vmax, S, Km):
"""
This function returns the initial reaction rate according to Michaelis-Menten kinetics
"""
v = Vmax * S * Km
return v
import numpy as np
Vmax=10
K_M = 2
S = 1
v=Vmax*S/(S+K_M)
v_codex = reaction_velocity(Vmax, S, K_M)
# check
if np.isclose(v, v_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
mol_charge
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
[insert]
return chargeimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def net_charge(smiles):
"""
This function returns net charge of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
charge = Chem.GetFormalCharge(mol)
return charge
s = 'C1([O-])C=CC=C1NC2CCCCCC2C3=CC=CC=C3'
result = True if net_charge(s) == -1 else FalseOutput:
Success
net_charge
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
[insert]
return chargeimport math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 65))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
|/
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += c
return charge
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
unsupported operand type(s) for +=: 'int' and 'str'
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(c.count('N'))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
math domain error
import math
import sys
def net_charge(sequence):
"""
This function returns net charge of amino acid sequence
"""
charge = 0
for c in sequence:
charge += math.log10(abs(ord(c) - 97))
return charge
result = True if net_charge("DSAVRCPQD") == -1 else FalseOutput:
Success
solve_ode
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
[insert]
return solimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for k in range(len(t)):
sol.append(fn(t[k], y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
sol[0] = y0
for i in range(1, len(t)):
sol[i] = sol[i-1] + fn(t[i], sol[i-1])
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
setting an array element with a sequence.
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = np.zeros(len(t))
sol[0] = y0
for i in range(1, len(t)):
sol[i] = sol[i-1] + fn(t[i], sol[i-1]) * dt
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
setting an array element with a sequence.
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def solve_ode(fn, t, y0):
"""
Solve an initial value problem for system of Ordinary Differential Equations using the Explicit Runge-Kutta method of order 5. t is a 1D vector and dy/dt=fn(t,y). Returns the values of the solution y at t.
"""
sol = []
for t in t:
sol.append(fn(t,y0))
return sol
from scipy.integrate import solve_ivp
def exponential_decay(t, y):
return -0.5 * y
solution = solve_ivp(exponential_decay, [0, 10], [4], t_eval=[2,5,8])
result = True if np.allclose(solution, solve_ode(exponential_decay, [2,5,8], [4])) else FalseOutput:
can't multiply sequence by non-int of type 'float'
ohe
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
[insert]
return vimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int)
v[a] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
v[a] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int)
v[a] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int32)
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
operands could not be broadcast together with shapes (10,) (10,5)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def ohe(a):
"""
This function generates one-hot encodings for
the class names in the given list of strings.
"""
v = np.zeros(len(a), dtype=np.int)
v[a] = 1
return v
import numpy as np
dog_breeds = ['German Shepherd', 'Husky',
'Bulldog', 'Dobermann', 'Great Dane', 'Husky', 'Bulldog', 'German Shepherd', 'Great Dane', 'German Shepherd']
unique_list = sorted(list(set(dog_breeds)))
n = len(dog_breeds)
m = len(unique_list)
ohe_array = np.zeros((n, m))
j = 0
for i in range(n):
ohe_array[j, unique_list.index(dog_breeds[i])] = 1.
j += 1
result = True if np.isclose(ohe(dog_breeds), ohe_array).all() else FalseOutput:
only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
osmotic_pressure
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
[insert]
return pimport math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = 0.025 # atm /mol
rho = 1.225 # atm /mol
rho_l = 1.225 # atm /mol
rho_h = 1.225 # atm /mol
rho_l = rho_l*math.pow(T,2)
rho_h = rho_h*math.pow(T,2)
rho_l = rho_l*math.pow(T,3)
rho_h = rho_h*math.pow(T,3)
rho_l = rho_l*math.pow(T,4)
rho_h = rho_h*math.pow(T,4)
rho_l = rho_l*math.pow(T,5)
rho_h = rho_h*math.pow(T,5)
rho_l = rho_l*math.pow(T,6)
rho_h = rho_h*math.pow(T,6)
rho_l = rho_l*math.pow(T,7)
rho_h = rho_h*math.pow(T,7)
rho_l = rho_l*math.pow(T,8)
rho_h = rho_h*math.pow(T,8)
rho_l = rho_l*math.pow(T,9)
rho_h = rho_h*math.pow(T,9)
rho_l = rho_l*math.pow(T,10)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/4.0)
p = p * math.pow(Pi,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R * math.pow(T,3.0/3.0)
p = p * math.pow(Pi,3.0/3.0)
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
Success
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 17)
import math
import sys
def osmotic_pressure_concentration(Pi,T):
"""
This function returns the concentration in mol/l given an osmotic pressure Pi and temperature T
T is in K
Pi is in atm
"""
R = 0.08206 # l atm /K /mol
p = R*math.pow(T,3.0/4.0)
p = p/math.pi
|/
return p
import numpy as np
pressure = 0.02 #atm
temperature = 310 #K
c = pressure/(0.08206*temperature)
result = True if np.abs(osmotic_pressure_concentration(pressure,temperature)-c)<0.01 else FalseOutput:
invalid syntax (<string>, line 18)
pair_wise
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
[insert]
return distancesimport mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros((alpha_carbons_length, alpha_carbons_length))
for i in range(alpha_carbons_length):
for j in range(alpha_carbons_length):
distances[i][j] = pdb.distances[i][j]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(i+1, len(alpha_carbons)):
distances[i][j] = np.linalg.norm(pdb.select('name *[name!= "Carbon"]')[alpha_carbons[i]:alpha_carbons[j]])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(str(pdb_file))
alpha_carbons = pdb.select('name CA')
alpha_carbons = alpha_carbons.sort('CA')
alpha_carbons = alpha_carbons.unique()
alpha_carbons = list(alpha_carbons)
alpha_carbons.sort()
distances = np.zeros((len(alpha_carbons), len(alpha_carbons)))
for i in range(len(alpha_carbons)):
for j in range(len(alpha_carbons)):
if i == j:
continue
distances[i][j] = alpha_carbons[i].distance(alpha_carbons[j])
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = mdtraj.load(pdb_file)
alpha_carbons = pdb.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
alpha_carbons = alpha_carbons.select('name *[name!= "Carbon"]')
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def pairwise_dist(pdb_file):
"""
1 This function loads a pdb
2 Selects only the alpha carbons
3 Calculates the number of unique alpha carbon pairs
4 Returns the distances between each alpha carbon pair
"""
pdb = md.load(pdb_file)
alpha_carbons = pdb.select('name *[name ~ "*"]')
alpha_carbons = alpha_carbons.unique()
alpha_carbons_length = len(alpha_carbons)
distances = np.zeros(alpha_carbons_length)
for i in range(alpha_carbons_length):
alpha_carbon = alpha_carbons[i]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
alpha_carbon = alpha_carbon.split()
alpha_carbon = alpha_carbon[0]
alpha_carbon = alpha_carbon[1:]
return distances
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_, "1VII.pdb")
def pairwise(pdb_file):
import mdtraj as md
from itertools import combinations
pdb = md.load(pdb_file)
cas = pdb.top.select("name CA")
distances = []
comb = combinations(cas, 2)
distances = md.compute_distances(pdb, comb, periodic=True)
return distances
my_result = pairwise(pdb_file)
nlcc_result = pairwise_dist(pdb_file)
#print("My result:", my_result)
#print("nlcc result", nlcc_result)
result = True if np.abs(np.mean(my_result) -
np.mean(nlcc_result)) < 0.01 else FalseOutput:
'Constant' object has no attribute 'kind'
pi
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
[insert]
return pi_estimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
pi = np.zeros(nsamples)
for i in range(nsamples):
pi[i] = pi_est
pi_est *= 1.
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = np.pi
pi_est *= nsamples
|/
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
invalid syntax (<string>, line 17)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 1.
for i in range(nsamples):
pi_est *= 1.
pi_est *= 1.
pi_est *= 1.
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 0
for i in range(nsamples):
pi_est = pi_est * np.pi / nsamples
return pi_est
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def pi(nsamples):
""" This function returns the value of pi by monte carlo sampling """
pi_est = 2*np.pi*np.random.random(nsamples)
|/ file dstars=0
return pi_est
result = True if np.abs(pi(10000)-3.14159265)<0.1 else FalseOutput:
invalid syntax (<string>, line 12)
pib_1d
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
[insert]
return eimport math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(m*L**2-L**2+hbar*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
for i in range(n+1):
e=e*math.exp(-0.5*hbar*L*i)
|/ file dstars=0
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=math.exp(-0.5*(n*m)/L)*hbar
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n*(L**2-m*hbar)
|/
|/
|/
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 14)
import math
import sys
def particle_in_box(n,m,L,hbar=1):
"""
This function returns the energy for a quantum particle in a 1d box
"""
e=n-m
if eL: return 0
L: return -hbar
if e==L: return hbar
return e
import numpy as np
import matplotlib.pyplot as plt
# input params
L = 10 # length of the box
m = 1 # masss of the particle
n = 10 # quantum number
hbar = 1 # planck constant
# energy
e_n = ((n**2)*(hbar**2)*(np.pi**2))/(2*m*L**2)
print("energy =", e_n)
e_n_codex = particle_in_box(n,m,L)
print("energy from codex =", e_n_codex)
# check
if abs(e_n - e_n_codex) <= 1e-3:
result = True
else:
result = False
Output:
invalid syntax (<string>, line 11)
pred_interval
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
[insert]
return nimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
pred_level:
return i
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
unindent does not match any outer indentation level (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = int(np.floor(np.log(p)/np.log(pred_level)))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
if p[i] pred_level:
return i
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for k in range(n):
if p[k] = pred_level:
return k
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
invalid syntax (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def num_trials(pred_level, p):
"""Returns the minimum number of trials needed to achieve
a probability given by pred_level in a geometric distribution
"""
n = len(p)
for i in range(n):
p = p * (1 - pred_level)
n = min(n, len(p))
return n
import numpy as np
prediction_level = 0.9
samples = range(1, 100)
p = 0.1
psum = 0
for n in samples:
psum += (1 - p) ** (n - 1) * p
if(psum >= prediction_level):
break
result = True if num_trials(prediction_level, p) == n else FalseOutput:
object of type 'float' has no len()
pubchem
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
[insert]
return molsimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/similarity?query={}&format=smiles'.format(smiles)
response = requests.get(url)
smiles = response.text
mols = Chem.MolFromSmiles(smiles)
mols = Chem.AddHs(mols)
mols = Chem.MolToSmiles(mols, canonical=True)
mols = Chem.MolFromSmarts(mols)
mols = Chem.RemoveHs(mols)
mols = Chem.RemoveAtoms(mols, rdMolHash.HashesToAtomMap)
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(0))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(3))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(6))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(7))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(8))
mols = Chem.RemoveAtoms(mols, Chem.AtomWithIdx(9))
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Python argument types in
rdkit.Chem.rdmolops.AddHs(NoneType)
did not match C++ signature:
AddHs(RDKit::ROMol mol, bool explicitOnly=False, bool addCoords=False, boost::python::api::object onlyOnAtoms=None, bool addResidueInfo=False)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=smiles'.format(smiles)
response = requests.get(url)
mol = Chem.MolFromSmiles(response.text)
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
mols = [mol for mol in mols if mol is not None]
mols = [Chem.MolFromSmiles(smiles) for smiles in response.text]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
mols = Chem.MolFromSmiles(smiles)
mols = [Chem.MolToSmiles(mol) for mol in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
mols = Chem.MolStandardize(mols)
mols = [Chem.MolFromSmiles(smiles) for smiles in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
'Mol' object is not iterable
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/search?query={}&format=sdf'.format(smiles)
response = requests.get(url)
data = response.json()
mols = []
for item in data['results']:
mols.append(Chem.MolFromSmiles(item['smiles'])) # Convert SMILES to Mol
mols = rdMolDescriptors.MolDescriptors.GetMorganFingerprintAsBitVect(mols, 2)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
mols = Scaffolds.MolWt(mols)
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
Expecting value: line 1 column 1 (char 0)
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
import requests
def find_similar(smiles):
"""
Returns a set of molecules with greater than 80% similarity using the PubChem REST API.
The returned molecules are SMILES strings, not CIDs.
"""
url = 'http://rest.pubchem.net/api/similarity?smiles=' + smiles
response = requests.get(url)
data = response.json()
mols = data['results']
mols = [Chem.MolFromSmiles(smi) for smi in mols]
return mols
import requests
import time
time.sleep(0.5)
def ref_find_similar(s):
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/fastsimilarity_2d/smiles/{s}/property/CanonicalSMILES/JSON"
reply = requests.get(
url,
params={"Threshold": 80, "MaxRecords": 100},
headers={"accept": "text/json"},
timeout=10,
)
data = reply.json()
smiles = [d["CanonicalSMILES"]
for d in data["PropertyTable"]["Properties"]]
smiles = set(smiles)
return smiles
s = 'CC=C=C(C(=O)N)'
ref_sim = ref_find_similar(s)
sim = find_similar(s)
result = True if ref_sim == set(sim) else FalseOutput:
HTTPConnectionPool(host='rest.pubchem.net', port=80): Max retries exceeded with url: /api/similarity?smiles=CC=C=C(C(=O)N) (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fbfc57883d0>: Failed to establish a new connection: [Errno -2] Name or service not known'))
pyscf_energy
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
[insert]
return ground_energyimport pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 29)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.split()]
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.verbose = 0
mol.output = None
mol.atom = [['H', (0., 0. , 0.)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
['H', (0., -0.757, 0.587)],
['H', (0., 0.757 , 0.587)],
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
invalid syntax (<string>, line 28)
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
mol.atom = [atom.name, atom.x, atom.y, atom.z]
mol.basis = basis
mol.build()
mol.verbose = 0
mol.output = None
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
import pyscf
import numpy as np
def calc_molecule_energy(atom,basis):
"""
This function returns the ground state energy for atom using restricted Hartree-Fock in the given basis
"""
mol = pyscf.gto.M(atom=atom,basis=basis)
mol.build()
mol.kernel()
ground_energy = mol.energy_nuc()
return ground_energy
atom_coordinates = "H 0 0 0; F 0 0 1"
basis = "sto-3g"
#so that it doesn't fail b/c not importing these in prompt:
from pyscf import gto, scf
def calc_molecule_energy_test(atom_coordinates,basis):
mol = gto.M(atom=atom_coordinates,basis=basis)
mf = scf.RHF(mol)
return mf.kernel()
my_energy = calc_molecule_energy_test(atom_coordinates,basis)
nlcc_energy = calc_molecule_energy(atom_coordinates,basis)
print("My result:", my_energy)
print("nlcc result:", nlcc_energy)
result = True if np.abs( my_energy - nlcc_energy )<0.1 else FalseOutput:
'NoneType' object has no attribute 'write'
qed
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
[insert]
return resultimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.MolToSmiles(mol)
mol = Chem.MolFromSmiles(smiles)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def qed(smiles):
"""
This function takes a SMILES string and returns the quantitative estimation of drug-likeness for the molecule.
"""
mol = Chem.MolFromSmiles(smiles)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
mol = Chem.AddHs(mol)
return result
from rdkit.Chem import QED
smiles = 'CC1=CN=C(C(=C1OC)C)CS(=O)C2=NC3=C(N2)C=C(C=C3)OC' # omeprazole
m = Chem.MolFromSmiles(smiles)
q = QED.qed(m)
result = True if np.isclose(qed(smiles), q) else False Output:
name 'result' is not defined
quantile
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
[insert]
return resultimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result.fill(np.nan)
result[np.where(aq)[0]] = np.nan
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
name 'aq' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(aq)] = np.nan
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
name 'aq' is not defined
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(a=q)] = np.quantile(a[np.where(a=q)], q)
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
where() got an unexpected keyword argument 'a'
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result.fill(np.nan)
q)]
result[np.where(aq)] = a[np.where(aq)]
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 13)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def quantile(a, q):
"""
This function computes the q-th quantile of the numpy array a. q can be a sequence of quantiles with values between 0 and 1 inclusive.
"""
result = np.zeros_like(a)
result[np.where(aq)] = np.nan
q)] = np.nan
return result
import numpy as np
np.random.seed(0)
M = 100
data = np.random.randint(1, M, size=(M,))
quantiles = [0.1, 0.5, 0.9]
result = True if np.allclose(
quantile(data, quantiles), np.quantile(data, q=quantiles)) else FalseOutput:
unmatched ')' (<string>, line 13)
random_walk
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
[insert]
return trajimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.rand()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn(1)
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
loop of ufunc does not support argument 0 of type numpy.ndarray which has no callable log method
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn(1)
traj.append(x1)
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.rand()
traj.append([x1, x0])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def random_walk(N):
"""
This function returns the trajectory of an N step random walk on a one dimensional lattice
"""
a = 1 # lattice spacing
x0 = 0
traj = []
for i in range(N):
x1 = x0 + a * np.random.randn()
traj.append([x0, x1])
x0 = x1
return traj
import numpy as np
import pylab as plt
nsteps = 5000
n_repeats = 250
nlcc_trj_list = []
for i in range(n_repeats):
nlcc_trj = random_walk(nsteps)
nlcc_trj_list.append(nlcc_trj)
nlcc_trj_list = np.array(nlcc_trj_list)
msd = (nlcc_trj_list*nlcc_trj_list).mean(axis=0)
a,b = np.polyfit(np.log(np.arange(1,nsteps)),np.log(msd[1:]),1)
#plt.plot(np.arange(nsteps),msd)
#plt.plot(np.arange(nsteps),np.exp(b+a*np.log(np.arange(nsteps))),linestyle='--',label='fit')
#plt.legend()
#plt.show()
#print("a =",a)
#print("b =",b)
#ideal exponent for msd is 1
ideal = 1.0
result = True if np.abs((a-ideal)/ideal) < 0.1 else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
ranks = np.linalg.matrix_rank(M)
ranks[ranks == 0] = 1
ranks[ranks == 1] = 0
return ranks
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
'numpy.int64' object does not support item assignment
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
ranks = np.linalg.matrix_rank(M)
ranks[ranks == 0] = 1
ranks[ranks == 1] = 0
r = ranks.argsort()
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
'numpy.int64' object does not support item assignment
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
ranks = np.linalg.matrix_rank(M)
ranks[ranks == 0] = 1
return ranks
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
'numpy.int64' object does not support item assignment
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
ranks = np.linalg.matrix_rank(M)
ranks[ranks == 0] = 1
ranks[ranks == 1] = 0
return ranks
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
'numpy.int64' object does not support item assignment
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
这个函数使用奇异值分解来计算矩阵M的秩。
"""
ranks = np.linalg.matrix_rank(M)
ranks = np.where(ranks == 0)[0]
r = ranks.copy()
ranks[ranks == 0] = 1
r[ranks == 0] = 1
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
Success
rank
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
[insert]
return rimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, S, V = np.linalg.svd(M)
r = np.argsort(np.abs(S))
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 17)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
rank = np.argsort(s)[::-1]
|/
|/
|/
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 17)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.argsort(s)
|/
|/
|/
|/
|/
|/
|/
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
invalid syntax (<string>, line 17)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
U, s, V = np.linalg.svd(M)
r = np.argsort(s)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rank(M):
"""
This function calculates the rank of matrix M using singular value decomposition.
"""
u, s, v = np.linalg.svd(M)
r = np.argsort(s)
return r
import numpy as np
np.random.seed(0)
M = np.random.random((5,5))
r = np.linalg.matrix_rank(M)
result = True if np.isclose(r, rank(M)) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
remove-water
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
[insert]
return new_trajimport mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
traj.top = traj.top.remove_solvent_from_topology(top_file)
new_traj = md.load(traj)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
traj = md.load(traj_file)
top = md.load(top_file)
new_traj = traj.remove_solvent_from_topology(top)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
import mdtraj as md
import numpy as np
def remove_water(traj_file,top_file):
"""
This function removes solvent from loaded trajectory traj_file and topology in top_file to return the new trajctory
"""
new_traj = md.load(traj_file)
new_traj.top = md.load(top_file)
return new_traj
import os
import mdtraj as md
traj = md.load(os.path.join(_FILE_DIR_,'trp-cage-small.trr'), top=os.path.join(_FILE_DIR_,'trp-cage.pdb'))
nowater = traj.remove_solvent()
result = True if remove_water(os.path.join(_FILE_DIR_,'trp-cage-small.trr'),os.path.join(_FILE_DIR_,'trp-cage.pdb')).n_atoms == nowater.n_atoms else False Output:
"top" argument is required for load_trr
rms_velocity
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
[insert]
return v_rms
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/3.0)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/(T*T))
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def rms_velocity(T,m):
"""
This function returns the root-mean-squared velocity of an ideal gas molecule at temperature T
m is mass in g/mol
"""
v_rms = math.sqrt(T*m*m/T)
return v_rms
import numpy as np
m=32
T=300
R=8.314
v_rms = np.sqrt(3*R*T/(m/1000))
v_rms_codex = rms_velocity(T,m)
# check
if np.isclose(v_rms, v_rms_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
rmse
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
[insert]
return eimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 14)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 16)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2)
|/
|/
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
invalid syntax (<string>, line 16)
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def rmse(a,b):
"""
This function evaluates the root mean square error (rmse) between a and b.
"""
e = np.sqrt((a-b)**2).mean()
return e
import numpy as np
np.random.seed(0)
M = 100
predictions = np.random.normal(loc=10, scale=3, size=(M,))
targets = np.random.normal(loc=9, scale=2, size=(M,))
test_rmse = np.sqrt(((predictions - targets) ** 2).mean())
result = True if np.isclose(rmse(predictions, targets), test_rmse) else FalseOutput:
Success
rog
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
[insert]
return rgimport mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = md.compute_radius_of_gyration(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
module 'mdtraj' has no attribute 'compute_radius_of_gyration'
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = mdtraj.distances.compute_radius_of_gyration(pdb)
|/
|/
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
invalid syntax (<string>, line 17)
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius(pdb)
return rg
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius' is not defined
import mdtraj as md
import numpy as np
def protein_radius_of_gyration(pdb_file):
"""
1. This function loads a pdb
2. Calculates the radius of gyration
3. Returns it
"""
pdb = md.load(pdb_file)
rg = protein_radius_of_gyration_from_pdb(pdb)
return rg
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_rg_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
rg = md.compute_rg(pdb)
return rg
my_rg = compute_rg_mdtraj(pdb_file)
nlcc_rg = protein_radius_of_gyration(pdb_file)
#print("My result:", my_rg)
#print("nlcc result", nlcc_rg)
result = True if np.abs( my_rg - nlcc_rg )<0.1 else False
Output:
name 'protein_radius_of_gyration_from_pdb' is not defined
sasa
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
[insert]
return sasaimport mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
sasa = sasa.residues.select('CA')
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('resname CA')
sasa.rename("CA")
|/
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
invalid syntax (<string>, line 16)
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = mdtraj.load(pdb_file)
sasa = pdb.select("resname like 'SASA%'")
sasa.compute_volume()
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
name 'mdtraj' is not defined
import mdtraj as md
import numpy as np
def protein_surface_area(pdb_file):
"""
1. This function loads a pdb
2. Calculates the Solvent Accessible Surface Area (sasa) per residue
3. Returns it
"""
pdb = md.load(pdb_file)
sasa = pdb.select('CA')
sasa = sasa.sum(axis=1).reshape(pdb.n_atoms, 1)
return sasa
import numpy as np
import sys
import os
pdb_file = os.path.join(_FILE_DIR_,"1VII.pdb")
def compute_sasa_mdtraj(pdb_file):
import mdtraj as md
pdb = md.load(pdb_file)
sasa = md.shrake_rupley(pdb,mode='residue')
return sasa
my_sasa = compute_sasa_mdtraj(pdb_file)
nlcc_sasa = protein_surface_area(pdb_file)
#print("My result:", my_sasa)
#print("nlcc result", nlcc_sasa)
result = True if np.abs( my_sasa.mean() - nlcc_sasa.mean() )<0.1 else FalseOutput:
'Trajectory' object has no attribute 'select'
scaffold
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
[insert]
return scaffold_smilesimport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
mol = Chem.MolFromSmiles(smiles)
scaffold_smiles = Chem.MolToSmiles(mol)
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def scaffold(smiles):
"""
Returns Murcko scaffold of given molecule
"""
scaffold_smiles = Chem.MolToSmiles(Chem.MolFromSmiles(smiles))
return scaffold_smiles
smiles = 'C1([O-])C=CC=C1NCC[NH+]'
mol = Chem.MolFromSmiles(smiles)
sc = rdkit.Chem.rdMolHash.MolHash(
mol, rdkit.Chem.rdMolHash.HashFunction.MurckoScaffold)
result = scaffold(smiles) == scOutput:
Success
seq-align
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
[insert]
return alignedfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.DONT_OVERLAP)
aln.set_score_mode(Align.SCORE_ABSOLUTE)
aln.set_evalue(0.0)
aln.set_evalue_threshold(0.0)
aln.set_score_file("blast.out")
aln.set_evalue_cutoff(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
aln.set_evalue_cutoff_threshold(0.05)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_open='-', gap_extend='-')
return aln.get_alignment_string()
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_open'
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([SeqIO.to_dict(SeqRecord(Seq(seq1), "fasta")), SeqIO.to_dict(SeqRecord(Seq(seq2), "fasta"))])
aln.set_flags(AlignInfo.SMART_AA_NAMES)
aln.set_flags(AlignInfo.SMART_aa)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
aln.set_flags(AlignInfo.INTRON)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'SeqRecord' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = AlignIO.read(seq1, 'fasta')
aln = AlignIO.read(seq2, 'fasta')
aln = AlignIO.read(aln, 'blast')
aln = AlignIO.read(aln, 'blastp')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
aln = AlignIO.read(aln, 'blastx')
aln = AlignIO.read(aln, 'blastn')
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
name 'AlignIO' is not defined
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def align(seq1, seq2):
'''
Align the two amino acid sequences with BLOSUM62 and return aligned sequences
'''
aln = Align.MultipleSeqAlignment([seq1, seq2], gap_char="-")
aln.set_flags(aln.get_flags() | Align.AUTO_SEQUENCE)
aln.set_score_mode(aln.get_score_mode() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue(0)
aln.set_score_func(aln.get_score_func() | Align.SCORE_ALIGNMENT_SCORE)
aln.set_evalue_threshold(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
aln.set_score_cutoff(0)
aln.set_evalue_cutoff(0)
return aligned
seq1 = Seq('EEKG')
seq2 = Seq('SSSDEKA')
a = align(seq1, seq2)
result = a[0] == '---EEKG'Output:
__init__() got an unexpected keyword argument 'gap_char'
seq-trans
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
[insert]
return prot_seqfrom Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
from Bio import SeqIO
from Bio import Align
from Bio import PopGen
from Bio.PDB import *
from Bio.Seq import Seq
import Bio
from Bio import pairwise2
from Bio.Blast import NCBIWWW, NCBIXML
from Bio.SubsMat import MatrixInfo as matlist
def nucleotide_translate(gene_seq):
"""
Converts nucleotide sequence to amino acids. Returns a string
"""
prot_seq = Seq(gene_seq)
return prot_seq
ns = 'atgaggtctttgctaatcttggtgctttgcttcctgcccctggctgctctggggaaagtctttggacgatgtgagctggcagcggctatgaagcgtcacggacttgataactatcggggatacagcctgggaaactgggtgtgtgctgcaaaattcgagagtaacttcaacacccaggctacaaaccgtaacaccgatgggagtaccgactacggaatcctacagatcaacagccgctggtggtgcaacgatggcaggaccccaggctccaggaacctgtgcaacatcccgtgctcagccctgctgagctcagacataacagcgagcgtgaactgcgcgaagaagatcgtcagcgatggaaacggcatgaacgcgtgggtcgcctggcgcaaccgctgcaagggcaccgacgtccaggcgtggatcagaggctgccggctgtga'
ps = 'MRSLLILVLCFLPLAALGKVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNRNTDGSTDYGILQINSRWWCNDGRTPGSRNLCNIPCSALLSSDITASVNCAKKIVSDGNGMNAWVAWRNRCKGTDVQAWIRGCRL'
tps = nucleotide_translate(ns)
result = ps in tpsOutput:
Success
sequence
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
[insert]
return ximport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s):
seq.append(i)
for i in range(e):
seq.append(i)
for i in range(l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s,e):
seq.append(i)
for i in range(s,e+l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s):
seq.append(i)
for i in range(s,e):
seq.append(i)
for i in range(s,e,l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
seq = []
for i in range(s):
seq.append(i)
for i in range(s,e):
seq.append(i)
for i in range(s,e+l):
seq.append(i)
return seq
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def gen_geometric_sequence(s,e,l):
"""
This function return a geometric sequence that starts at s, ends at e with length l
"""
x = np.arange(s,e,l)
|/
|/
|/
|/
|/
return x
result = True if np.all(gen_geometric_sequence(1,100,3)== [1,10,100]) else FalseOutput:
invalid syntax (<string>, line 17)
sle
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
[insert]
return ximport sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs([('a_0x_0', 'c0'), ('a_1x_0', 'c1')])
eqns = eqns.subs([('b_0x_1', 'c0'), ('b_1x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
eqns = eqns.subs([('x_0', 'c0'), ('x_1', 'c1')])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('c_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('c_0x_0 = c0')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
a = eqns[0]
b = eqns[1]
c = eqns[2]
d = eqns[3]
e = eqns[4]
f = eqns[5]
g = eqns[6]
h = eqns[7]
i = eqns[8]
j = eqns[9]
k = eqns[10]
l = eqns[11]
m = eqns[12]
n = eqns[13]
o = eqns[14]
p = eqns[15]
q = eqns[16]
r = eqns[17]
s = eqns[18]
t = eqns[19]
u = eqns[20]
v = eqns[21]
w = eqns[22]
x = sympy.Matrix([[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p],[q,r,s,t,u,v,w,x,y,z,w]])
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
import sympy
def sle(eqns):
"""
This function solves a system of linear equations {['a_0x_0 + b_0x_1 = c0','a_1x_0 + b_1x_1 = c1']}.
"""
eqns = sympy.sympify(eqns)
x = sympy.symbols('x')
eqns = eqns.subs({x:sympy.symbols('a_0x_0 + b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 + b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_0 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_0 = c1')})
eqns = eqns.subs({x:sympy.symbols('b_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('b_1x_1 = c1')})
eqns = eqns.subs({x:sympy.symbols('a_0x_1 = c0')})
eqns = eqns.subs({x:sympy.symbols('a_1x_1 = c1')})
return x
from sympy import solve, Eq
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.sympy_parser import standard_transformations, implicit_multiplication_application
eqns = ['4x + 3y = 20', '-5x + 9y = 26']
transformations = (standard_transformations +
(implicit_multiplication_application,))
parsed_eqs = []
for eq in eqns:
sides = [parse_expr(s, transformations=transformations)
for s in eq.split('=')]
parsed_eqs.append(Eq(sides[0], sides[1]))
soln = solve(parsed_eqs)
test_sol_values = [soln.get(list(soln.keys())[0]), soln.get(list(soln.keys())[1])]
result = True if list(sle(eqns).values()) == test_sol_values else FalseOutput:
Sympify of expression 'could not parse '4x + 3y = 20'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
spectral_r
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
[insert]
return sradiusimport numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2,1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a ** 2)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2, axis=1)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def spectral_r(a):
"""
This function calculates the spectral radius of the input square matrix a.
"""
sradius = np.sum(a**2)
return sradius
import numpy as np
np.random.seed(0)
M = 100
a = np.random.normal(loc=10, scale=3, size=(M,M))
eig = np.linalg.eigvals(a)
s_r = np.amax(np.absolute(eig))
result = True if np.isclose(spectral_r(a), s_r) else FalseOutput:
Success
find_peaks
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
[insert]
return wavenumbersimport numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for peak in peaks:
wavenumbers.append(peak[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peak_positions, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peak_positions = np.asarray(peak_positions)
peak_positions.sort()
peak_positions = peak_positions[::-1]
peak_positions = peak_positions[:npeaks]
return peak_positions
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = np.asarray(peaks)
peaks.sort()
peaks = peaks[:npeaks]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
peaks = peaks[::-1]
peaks = [peaks[i] for i in xrange(len(peaks))]
return peaks
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
import numpy as np
import scipy
import scipy.optimize
import scipy.signal
def find_peaks(abs_spectrum, npeaks=3):
''' This will find the highest `npeaks` peaks and return a list of peak wavenumbers.
`abs_spectrum` should be shape (N, 2)
'''
peaks, _ = scipy.signal.find_peaks(abs_spectrum, height=npeaks)
wavenumbers = []
for p in peaks:
wavenumbers.append(p[0])
return wavenumbers
s = np.loadtxt(
'https://raw.githubusercontent.com/whitead/numerical_stats/master/unit_12/lectures/spectrum.txt')
# clean up to be like an absorption spectrum
s[:, 1] /= np.max(s[:, 1])
ints = np.array(find_peaks(s, 4))
true = [609, 645, 670]
result = len(ints) == 4
for t in true:
result = result and np.any(np.abs(ints - t) < 5)Output:
`x` must be a 1-D array
speed_of_sound
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
[insert]
return s
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m * gamma * T
if __name__ == "__main__":
T = int(sys.argv[1])
m = float(sys.argv[2])
gamma = float(sys.argv[3])
print speed_of_sound(T,m,gamma)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
invalid syntax (<string>, line 16)
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = m*T*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*math.exp(-gamma*T)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
import math
import sys
def speed_of_sound(T,m,gamma):
"""
This function returns the speed of sound for an ideal gas at temperature T
m is mass in g/mol
"""
s = T*m*gamma
s = math.floor(s)
return s
import numpy as np
M=28
T=300
R=8.314
gamma=7/5
s = np.sqrt(gamma*R*T/(M/1000))
s_codex = speed_of_sound(T,M,gamma)
# check
if np.isclose(s, s_codex, rtol=0.01) == True:
result = True
else:
result = FalseOutput:
Success
substructure
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
[insert]
return idximport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.AddHs(mol_list)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = Chem.AddHs(mol_list)
mol_list = Chem.RemoveHs(mol_list)
mol_list = Chem.RemoveAtoms(mol_list, 1)
mol_list = Chem.RemoveAtoms(mol_list, 2)
mol_list = Chem.RemoveAtoms(mol_list, 3)
mol_list = Chem.RemoveAtoms(mol_list, 4)
mol_list = Chem.RemoveAtoms(mol_list, 5)
mol_list = Chem.RemoveAtoms(mol_list, 6)
mol_list = Chem.RemoveAtoms(mol_list, 7)
mol_list = Chem.RemoveAtoms(mol_list, 8)
mol_list = Chem.RemoveAtoms(mol_list, 9)
mol_list = Chem.RemoveAtoms(mol_list, 10)
mol_list = Chem.RemoveAtoms(mol_list, 11)
mol_list = Chem.RemoveAtoms(mol_list, 12)
mol_list = Chem.RemoveAtoms(mol_list, 13)
mol_list = Chem.RemoveAtoms(mol_list, 14)
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def substructure(smiles, mol_list):
"""
This function takes a smiles string and searches mol_list to find entries that contain the substructure. It returns the indices of these entries.
"""
mol_list = Chem.MolFromSmiles(smiles)
mol_list = [Chem.MolFromSmiles(smiles) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
mol_list = [Chem.MolFromSmiles(smi) for smi in mol_list]
return idx
import numpy as np
import os
# Taken from rdkit Docs
from rdkit import RDConfig, Chem
from rdkit.Chem import rdSubstructLibrary
library = rdSubstructLibrary.SubstructLibrary()
llibrary = []
for mol in Chem.SDMolSupplier(os.path.join(RDConfig.RDDataDir,
'NCI', 'first_200.props.sdf')):
idx = library.AddMol(mol)
llibrary.append(mol)
smiles = 'CCCCOC'
core = Chem.MolFromSmiles(smiles)
indices = library.GetMatches(core)
result = True if np.isclose(len(substructure(
smiles, llibrary)), len(indices)) else FalseOutput:
File error: Bad input file /tmp/pip-req-build-p3aa6g65/build/temp.linux-x86_64-3.8/rdkit_install/share/RDKit/Data/NCI/first_200.props.sdf
tanimoto
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
[insert]
return simport matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("NumAtomPairs", len(smiles_list))
scaffold.SetProp("NumExplicitHs", 0)
scaffold.SetProp("NumImplicitHs", 0)
scaffold.SetProp("NumRotatableBonds", 0)
scaffold.SetProp("NumPeriodicBonds", 0)
scaffold.SetProp("NumBonds", 0)
scaffold.SetProp("NumBondBonds", 0)
scaffold.SetProp("NumHs", 0)
scaffold.SetProp("NumHsAtomPairs", 0)
scaffold.SetProp("NumHsBonds", 0)
scaffold.SetProp("NumHsBondBonds", 0)
scaffold.SetProp("NumHsBondBondBonds", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("NumBits", bits)
scaffold.SetProp("MurckoPhi", True)
scaffold.SetProp("MurckoPhiBits", bits)
scaffold.SetProp("MurckoPhiPrecision", bits)
scaffold.SetProp("MurckoPhiMinBits", bits)
scaffold.SetProp("MurckoPhiMaxBits", bits)
scaffold.SetProp("MurckoPhiSeed", 0)
scaffold.SetProp("MurckoPhiSeedBits", bits)
scaffold.SetProp("MurckoPhiSeedPrecision", bits)
scaffold.SetProp("MurckoPhiSeedMinBits", bits)
scaffold.SetProp("MurckoPhiSeedMaxBits", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.SetProp("GenerateMurckoFlag", 0)
scaffold.SetProp("MurckoBits", bits)
scaffold.SetProp("MurckoPhi", 3)
scaffold.SetProp("MurckoMinVal", 0)
scaffold.SetProp("MurckoSeed", 0)
scaffold.SetProp("MurckoSeed2", 0)
scaffold.SetProp("MurckoSeed3", 0)
scaffold.SetProp("MurckoSeed4", 0)
scaffold.SetProp("MurckoSeed5", 0)
scaffold.SetProp("MurckoSeed6", 0)
scaffold.SetProp("MurckoSeed7", 0)
scaffold.SetProp("MurckoSeed8", 0)
scaffold.SetProp("MurckoSeed9", 0)
scaffold.SetProp("MurckoSeed10", 0)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyError", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyWarning", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracy", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAccuracyAccuracyError", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
import matplotlib.pyplot as plt
import rdkit
from rdkit import Chem
from rdkit.Chem import Draw
from rdkit.Chem import rdMolHash
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Scaffolds
from rdkit.Chem import Crippen
from rdkit.Chem import Descriptors
from rdkit.ML.Descriptors import MoleculeDescriptors
from rdkit import DataStructs
from rdkit.Chem import Scaffolds
import numpy as np
def tanimoto_matrix(smiles_list, bits=256):
"""
Returns pairwise Tanimoto similarity matrix with ECFP4 fingerprints
"""
scaffold = Scaffolds.MurckoScaffold()
scaffold.Compute2DCoords()
scaffold.SetProp("Compute2DCoords", True)
scaffold.SetProp("MurckoScaffoldParams.NumBits", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsFingerprint", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAtom", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsBondAngle", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHBond", bits)
scaffold.SetProp("MurckoScaffoldParams.NumBitsHAngle", bits)
return s
import numpy as np
from rdkit.DataStructs.cDataStructs import TanimotoSimilarity
from rdkit.Chem import AllChem
from rdkit import Chem
import itertools
def ref_tan_matrix(slist):
fp = [AllChem.GetMorganFingerprintAsBitVect(
Chem.MolFromSmiles(s), 2, nBits=256) for s in slist]
ts = list(
TanimotoSimilarity(x, y) for x, y in itertools.product(fp, repeat=2)
)
return np.array(ts).reshape(len(fp), len(fp))
mols = ['C1C=C(C=NC=C(C(F)(F)F)CCCCCC)C=C1C=CC=CC',
'CC=C=C(C(=O)N)', 'C1([O-])C=CC=C1NC=CC=C']
# turned down tolerance because CODEX wants to compute
# fingerprint with slightly different implementation (can't tell diff?)
result = True if np.allclose(ref_tan_matrix(
mols), tanimoto_matrix(mols), rtol=0.1, atol=1e-2) else FalseOutput:
module 'rdkit.Chem.Scaffolds' has no attribute 'MurckoScaffold'
unbdistance
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
[insert]
return resultimport mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=md.resids[lig_str]
lig_traj = md.load(traj,top=lig_resid).get_frame(0)
lig_traj = lig_traj[lig_traj.select('resname '+lig_str)]
lig_traj = lig_traj[lig_traj.select('name '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
lig_traj = lig_traj[lig_traj.select('chain '+lig_str)]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_resid=lig_str.split("_")
lig_resid=lig_resid[0]
lig_resid=lig_resid[1:]
lig_resid=lig_resid.split(":")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("(")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split(")")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("+")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("-")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("*")
lig_resid=lig_resid[0]
lig_resid=lig_resid.split("=")
lig_resid=lig_resid[0]
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_atoms = traj.resids[lig_str]
lig_atoms_center = lig_atoms.center()
lig_atoms_center = np.array(lig_atoms_center)
lig_atoms_center = lig_atoms_center.reshape((1,3))
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
lig_atoms_center = lig_atoms_center.T
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_str = lig_str.upper()
lig_atoms = md.get_atoms(traj,resname=lig_str)
lig_atoms = lig_atoms.reshape((-1,3))
lig_atoms[:,0] += traj[0].xyz[0]
lig_atoms[:,1] += traj[0].xyz[1]
lig_atoms[:,2] += traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
lig_atoms[:,2] /= len(traj)
lig_atoms[:,0] -= traj[0].xyz[0]
lig_atoms[:,1] -= traj[0].xyz[1]
lig_atoms[:,2] -= traj[0].xyz[2]
lig_atoms[:,0] /= len(traj)
lig_atoms[:,1] /= len(traj)
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'
import mdtraj as md
import numpy as np
def unbdistance(traj,lig_str):
"""
This function returns a list of distances between center of mass of
protein and center of mass of lig_str in every frame of trajectory
traj
traj is an mdtraj trajectory object
lig_str is a string with the residue name of the ligand
"""
lig_traj = md.load(lig_str)
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
lig_traj = md.load('lig_traj.xyz')
lig_traj.compute_center_of_mass()
lig_traj.save('lig_traj.xyz')
return result
import mdtraj as md
import os
import math
import numpy as np
#_FILE_DIR_ = '.'
lig_str = 'TMP'
traj_path = os.path.join(_FILE_DIR_, 'traj.dcd')
top_path = os.path.join(_FILE_DIR_, 'top.pdb')
traj = md.load(traj_path, top=top_path)
top = traj.topology
prot_idxs = top.select('protein')
lig_idxs = top.select(F'resname == {lig_str}')
traj2 = md.load(traj_path, atom_indices=prot_idxs, top=top_path)
traj3 = md.load(traj_path, atom_indices=lig_idxs, top=top_path)
dist = []
for i,j in zip(traj2,traj3):
com_a = md.compute_center_of_mass(i)[0]
com_b = md.compute_center_of_mass(j)[0]
dist.append(((com_a[0]-com_b[0])**2+(com_a[1]-com_b[1])**2+(com_a[2]-com_b[2])**2)**0.5)
# assert
distances = unbdistance(traj,lig_str)
check = math.isclose(dist[0],distances[0])
check2 = math.isclose(dist[-1],distances[-1])
result = True if check and check2 else False Output:
'Constant' object has no attribute 'kind'